// reference local blank image
Ext.BLANK_IMAGE_URL = '../javascripts/mfbase/stylesheets/ext/resources/images/default/s.gif';

var gsat, gsat2, map, toolbar, viewport, popup, propGrid, cur_map;
var radars, radnames, totRadars, loopable, logWind, pnl_html = '', logStart;
var green, river, building, roads, markers, layer_style_9, layer_style_18, vectorLayer_9, vectorLayer_18, vectorLayer;
var field900_cell, field1800_cell, traffic900_cell, traffic1800_cell;
var prev_900_id = 0, prev_1800_id = 0, mark_gridid = 0;
var prev_900_hw = 0, prev_1800_hw = 0;
var cur_date = 'now', cur_time = 'val8'; // cells, cells_20091227 if select
// chage
// to '_20091227'

var showFans = false, showMode = 0; // 0 = all, 1 = 900 sector, 2=1800 sectore,
// 3 others
var transtoolon = true;
var host_url = "http://192.168.0.102:8080/geoserver/wms";
var base_url = "http://192.168.0.102:8080/geoserver/wms";
var format = "image/png";

var markWind, hover;

var __GOOGLE__ = true;

/*
 * ! 获取最新纪录日期赋值给session：cur_date new Ajax.Request("/map/set_cur_date", { method :
 * 'POST', parameters : 'cur_date=now' });
 */

// Ext.dd.DragDropMgr.clickTimeThresh = 1000;
// Ext.QuickTips.init();
OpenLayers.Control.Hover = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions : {
        'delay' : 150,
        'pixelTolerance' : null,
        'stopMove' : false
    },

    initialize : function(options) {
        this.handlerOptions = OpenLayers.Util.extend({},
            this.defaultHandlerOptions);
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.handler = new OpenLayers.Handler.Hover(this, {
            'pause' : this.onPause,
            'move' : this.onMove
        }, this.handlerOptions);
    },

    onPause : function(evt) {
        // var output = document.getElementById(this.key + 'Output');
        // var msg = 'pause ' + evt.xy;
        // output.value = output.value + msg + "\r\n";
        var pt = map.getLonLatFromPixel(evt.xy);
        var gridid = getGridid(pt.lon, pt.lat);

        if (gridid > 0 && mark_gridid != gridid && !markWind.hidden
            && markWind.items['items'][0].activeTab.title == '监视') {
            mark_gridid = gridid;

            var pars = 'gridid=' + mark_gridid;
            new Ajax.Request("/map/getValue9", {
                method : "POST",
                parameters : pars,
                onComplete : function(request) {
                    var vals = eval("(" + request.responseText + ")");
                    var cell = vals[0]["user"];
                    var cell_gridid = cell["grid_id"];
                    var dist = get_distiance(mark_gridid, cell_gridid);
                    // var markProp =
                    // markWind.items['items'][0].items['items'][2].items['items'][0];
                    var markProp = markWind.items['items'][0].items['items'][3].items['items'][0].items['items'][0].items['items'][0];

                    markProp.setSource({
                        // '02_坐标' :
                        // Ext.util.Format.number(pt.lon,'0,0.00') + '
                        // '+ Ext.util.Format.number(pt.lat,'0,0.00'),
                        '01_grid_id' : gridid,
                        '02_距离' : Ext.util.Format
                        .number(dist, '0,0.00')
                        + 'm',
                        '03_基站名' : cell["basename"],
                        '04_基站名称' : cell["cell_id"],
                        '05_基站地址' : cell["addr"],
                        '06_场强值' : cell["val_0"],
                        '07_话务值' : cell["val25"]
                    });

                    new Ajax.Request("/map/getValue18", {
                        method : "POST",
                        parameters : pars,
                        onComplete : function(request) {
                            var vals = eval("(" + request.responseText + ")");
                            var cell = vals[0]["user"];
                            var cell_gridid = cell["grid_id"];
                            var dist = get_distiance(mark_gridid, cell_gridid);
                            // var markProp =
                            // markWind.items['items'][0].items['items'][2].items['items'][0];
                            var markProp = markWind.items['items'][0].items['items'][3].items['items'][0].items['items'][1].items['items'][0];
                            markProp.setSource({
                                // '02_坐标' :
                                // Ext.util.Format.number(pt.lon,'0,0.00')
                                // + ' '+
                                // Ext.util.Format.number(pt.lat,'0,0.00'),
                                '01_grid_id' : gridid,
                                '02_距离' : Ext.util.Format.number(dist,
                                    '0,0.00')
                                + 'm',
                                '03_基站名' : cell["basename"],
                                '04_基站名称' : cell["cell_id"],
                                '05_基站地址' : cell["addr"],
                                '06_场强值' : cell["val_0"],
                                '07_话务值' : cell["val25"]
                            });
                        }
                    }); // end of new Ajax 1800

                } // end of onComplete
            });

        }; // end if

        if (gridid > 0 && mark_gridid != gridid && !markWind.hidden
            && markWind.items['items'][0].activeTab.title == '当前图层') {
            mark_gridid = gridid;

            var pars = 'gridid=' + mark_gridid;
            new Ajax.Request("/map/get_mark_info", {
                method : "POST",
                parameters : pars,
                onComplete : function(request) {
                    // var vals = eval("("+request.responseText+")");
                    var markProp = markWind.items['items'][0].items['items'][2].items['items'][0];
                    markProp.setSource({
                        '01_grid_id' : mark_gridid,
                        '02_大楼' : '',
                        '03_道路' : '',
                        '04_水系' : ''
                    });
                }
            });

        }; // end if

    },

    onMove : function(evt) {
    // if this control sent an Ajax request (e.g. GetFeatureInfo) when
    // the mouse pauses the onMove callback could be used to abort that
    // request.
    // var pt = map.getLonLatFromPixel(evt.xy);
    // var gridid = getGridid(pt.lon, pt.lat);
    }
});

function getGridid(x, y) {
    return (1 + Math.floor((x - 12572400) / 5) + Math.floor((y - 2575200) / 5)
        * 25160);
}

setTimeout(function() {
    Ext.get('loading').remove();
    Ext.get('loading-mask').fadeOut({
        remove : true
    });
}, 10000);

Ext.onReady(function() {

    Ext.QuickTips.init();
    // pink tile avoidance
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
    OpenLayers.Util.onImageLoadErrorColor = 'transparent';

    // make OL compute scale according to WMS spec
    OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;

    // Map Component
    var tm5 = 0.5;
    var tm6 = 0.6;
    var tm7 = 0.7;
    var tm8 = 0.8;
    var zoomlevel = 5; // 12:2km, 13:1km, 14: 500m, 15:200m, 16: 100m, 17:50m,
    // 18:20m, 19:10 m
    // var zoomlevel = 5; //1:5km 2:2km, 3:1km, 4: 500m, 5:200m, 6: 100m, 7:50m,
    // 8:20m, 9:10 m

    var options = {
        projection : new OpenLayers.Projection('EPSG:4326'),
        units : "m",
        maxResolution : 152.87405654296876,
        maxExtent : new OpenLayers.Bounds(-2.003750834E7, -2.003750834E7,
            2.003750834E7, 2.003750834E7),
        tileSize : new OpenLayers.Size(256, 256)
    };

    map = new OpenLayers.Map($('center'), options);

    if (__GOOGLE__) {

        // create Google Mercator layers
        try {
            gsat = new OpenLayers.Layer.Google("gsat", {
                type : G_HYBRID_MAP,//G_SATELLITE_3D_MAP,//G_HYBRID_MAP,
                "sphericalMercator" : true,
                opacity : 1,
                minZoomLevel : 13,
                maxZoomLevel : 24
            });
            map.addLayers([gsat]);

            gsat2 = new OpenLayers.Layer.Google("gsat2", {
                type : G_SATELLITE_3D_MAP
            //						"sphericalMercator" : true
            });
            map.addLayers([gsat2]);
        } catch (e) {
            alert("无法连接到Google Map，卫星地图将不能显示！");
        }

        // add one layer from WMS
        var geom_group = new OpenLayers.Layer.WMS("geom_group", host_url, {
            layers : 'geom_group',
            srs : 'EPSG:4326',
            transparent : false,
            opacity : 1,
            format : format,
            minZoomLevel : 10,
            maxZoomLevel : 21
        }, {
            isBaseLayer : true
        });
        map.addLayer(geom_group);

    } else {
        // add one layer from WMS
        var geom_group = new OpenLayers.Layer.WMS("geom_group", host_url, {
            layers : 'geom_group',
            srs : 'EPSG:4326',
            transparent : false,
            opacity : 1,
            format : format,
            minZoomLevel : 10,
            maxZoomLevel : 21
        }, {
            isBaseLayer : true
        });
        map.addLayer(geom_group);
    }

    var s_option6 = {
        reproject : false,
        opacity : tm6,
        visibility : false,
        isBaseLayer : false
    };
    var s_option5 = {
        reproject : false,
        opacity : 1,
        visibility : false,
        isBaseLayer : false,
        displayInLayerSwitcher : false
    };

    var blank = new OpenLayers.Layer.WMS("blank", host_url, {
        layers : 'GZ125:smallgz',
        srs : 'EPSG:4326',
        transparent : true,
        format : format
    }, s_option5);
    map.addLayer(blank);

    green = new OpenLayers.Layer.WMS("green", host_url, {
        layers : 'GZ125:green',
        srs : 'EPSG:4326',
        transparent : true,
        format : format
    }, s_option6);
    map.addLayer(green);

    river = new OpenLayers.Layer.WMS("river", host_url, {
        layers : 'GZ125:river',
        srs : 'EPSG:4326',
        transparent : true,
        format : format
    }, s_option6);
    map.addLayer(river);

    building = new OpenLayers.Layer.WMS("building", host_url, {
        layers : 'GZ125:building',
        srs : 'EPSG:4326',
        transparent : true,
        format : format
    }, s_option5);
    map.addLayer(building);

    // roads
    roads = new OpenLayers.Layer.WMS("roads", host_url, {
        layers : 'roads',
        srs : 'EPSG:4326',
        transparent : true,
        format : format
    }, s_option5);
    map.addLayer(roads);

    // add vector layer for gsm900
    layer_style_9 = OpenLayers.Util.extend({},
        OpenLayers.Feature.Vector.style['default']);
    layer_style_9.fillColor = "#F67F09";
    layer_style_9.strokeColor = "#F67F09";
    vectorLayer_9 = new OpenLayers.Layer.Vector("vectorLayer_9", {
        style : layer_style_9
    });
    // vectorLayer_9 = new OpenLayers.Layer.Vector("vectorLayer_9");

    // add vector layer for gsm1800
    layer_style_18 = OpenLayers.Util.extend({},
        OpenLayers.Feature.Vector.style['default']);
    layer_style_18.fillColor = "#1432C7";
    layer_style_18.strokeColor = "#1432C7";
    vectorLayer_18 = new OpenLayers.Layer.Vector("vectorLayer_18", {
        style : layer_style_18
    });

    // own draw fan layers
    vectorLayer = new OpenLayers.Layer.Vector("vector", {
        displayInLayerSwitcher : true
    });

    // Add Icon Maker Layer here
    markers = new OpenLayers.Layer.Markers("Markers");
    map.addControl(new OpenLayers.Control.Graticule({
        numPoints : 2,
        labelled : true,
        visible : true
    }));

    map.addLayers([vectorLayer_9, vectorLayer_18, vectorLayer, markers]);

    // toolbar Settings
    toolbar = new mapfish.widgets.toolbar.Toolbar({
        map : map,
        configurable : false
    });
    // toolbar.autoHeight = true;
    toolbar.height = 30;

    // Add Map controls
    // map.addControl(new OpenLayers.Control.LayerSwitcher());
    // map.addControl(new OpenLayers.Control.Permalink('permalink'));
    map.addControl(new OpenLayers.Control.Scale($('scale')));
    map.addControl(new OpenLayers.Control.MousePosition());
    // map.addControl(new OpenLayers.Control.MouseToolbar());
    // map.addControl(new OpenLayers.Control.Navigation({'zoomWheelEnabled':
    // true}));
    // map.addControl(new OpenLayers.Control.ScaleLine());

    hover = new OpenLayers.Control.Hover({
        handlerOptions : {
            'delay' : 200
        // 'pixelTolerance': 3
        }
    });
    map.addControl(hover);

    var controls = map.getControlsByClass('OpenLayers.Control.Navigation');
    for (var i = 0; i < controls.length; ++i)
        controls[i].disableZoomWheel();

    // set center and level
    var lonLat = new OpenLayers.LonLat(12613590, 2646380);
    map.setCenter(lonLat, zoomlevel);

    // setting models
    var model = [{
        text : "底图选择",
        expanded : false,
        children : [{
            text : "Google卫星影像",
            checked : true,
            layerName : "gsat"
        }, {
            text : "3D地图",
            checked : true,
            layerName : "gsat2"
        }, {
            text : "矢量地图",
            checked : true,
            layerName : "geom_group"
        }]
    }, {
        text : "背景图层",
        checked : true,
        expanded : false,
        children : [{
            text : "白底色",
            checked : false,
            layerName : "blank"
        }, {
            text : "建筑",
            checked : false,
            layerName : "building"
        }, {
            text : "道路",
            checked : false,
            layerName : "roads"
        }, {
            text : "绿地",
            checked : false,
            layerName : "green"
        }, {
            text : "河流",
            checked : false,
            layerName : "river"
        }, {
            text : "矢量图层1",
            checked : true,
            layerName : "vectorLayer_9"
        }, {
            text : "矢量图层2",
            checked : true,
            layerName : "vectorLayer_18"
        }, {
            text : "绘制天线",
            checked : true,
            layerName : "vector"
        }, {
            text : "经纬线",
            checked : true,
            layerName : "Graticule"
        }, {
            text : "标记",
            checked : true,
            layerName : "Markers"
        }]
    }, {
        text : "当前图层",
        checked : false,
        expanded : true,
        children : [{
            text : "GSM900",
            checked : false,
            expanded : true,
            children : []
        }, {
            text : "GSM1800",
            checked : false,
            expanded : true,
            children : []
        }]
    }, {
        text : "收藏图层",
        checked : false,
        expanded : true,
        children : []
    }];

    map.events.register("click", map, function(e) {
        var pt = this.getLonLatFromPixel(e.xy);
        var gridid = getGridid(pt.lon, pt.lat);

        if (gridid > 0) {
            var innerHtml = "";
            add(pt.lon, pt.lat, "/images/AQUA.png", innerHtml, true);
            Event.stop(e);
        }
    });

    var formatColor = function(value) {
        return String
        .format(
            '<div><span style="color:black;background-color:{0};">&nbsp&nbsp&nbsp{0}&nbsp&nbsp&nbsp</span></div>',
            value);
    };

    var formatId = function(value) {
        return String
        .format(
            '<div><span style="color:black;background-color:#{0};">{0}</span></div>',
            value);
    };

    // Field Lengend
    var store_field = new Ext.data.Store({
        proxy : new Ext.data.HttpProxy({
            url : '/map/getstyle'
        }),

        reader : new Ext.data.JsonReader({
            totalProperty : 'results',
            root : 'rows',
            fields : [{
                name : 'id'
            }, {
                name : 'cond',
                type : 'string'
            }, {
                name : 'color',
                type : 'string'
            }]
        })
    });

    var grid_field = new Ext.grid.GridPanel({
        store : store_field,
        columns : [{
            id : 'id',
            header : '编号',
            width : 25,
            sortable : true,
            dataIndex : 'id'
        }, {
            header : '条件',
            width : 75,
            dataIndex : 'cond'
        }, {
            header : '颜色',
            width : 50,
            sortable : true,
            renderer : formatColor,
            dataIndex : 'color'
        }],
        stripeRows : true,
        height : 300,
        width : 180,
        title : '-'
    });

    var treePanel = new Ext.tree.TreePanel({
        useArrows : true,
        animate : true,
        enableDD : true,
        checkModel : 'cascade',
        onlyLeafCheckable : false,
        collapsible : true,
        collapseMode : 'mini',
        loader : new Ext.tree.TreeLoader({
            dataUrl : 'map/gettree',
            baseAttrs : {
                uiProvider : Ext.ux.TreeCheckNodeUI
            }
        }),
        root : {
            nodeType : 'async',
            text : 'GZ Mobile',
            draggable : false,
            id : 'root'
        }
    });

    // Favarite tree
    var treeFavor = new Ext.tree.TreePanel({
        useArrows : true,
        animate : true,
        enableDD : true,
        checkModel : 'cascade',
        onlyLeafCheckable : false,
        collapsible : true,
        collapseMode : 'mini',
        loader : new Ext.tree.TreeLoader({
            dataUrl : 'map/getfavor_time',
            baseAttrs : {
                uiProvider : Ext.ux.TreeCheckNodeUI
            }
        }),
        root : {
            nodeType : 'async',
            text : '我的收藏',
            draggable : false,
            id : 'root'
        }
    });

    var favorBar = new Ext.Toolbar({
        items : [{
            xtype : 'tbspacer'
        }, {
            xtype : 'tbbutton',
            text : '按时间',
            handler : function() {
                treeFavor.loader.dataUrl = '/map/getfavor_time';
                treeFavor.getRootNode().reload();
            }
        }, {
            xtype : 'tbspacer'
        }, {
            xtype : 'tbbutton',
            text : '按名称',
            handler : function() {
                treeFavor.loader.dataUrl = '/map/getfavor_name';
                treeFavor.getRootNode().reload();
            }
        }, {
            xtype : 'tbspacer'
        }, {
            xtype : 'tbbutton',
            text : '按用户',
            handler : function() {
                treeFavor.loader.dataUrl = '/map/getfavor_user';
                treeFavor.getRootNode().reload();
            }
        }]
    });

    // layers Store
    var store_layer = new Ext.data.Store({
        proxy : new Ext.data.HttpProxy({
            url : '/map/getLayerStore'
        }),
        reader : new Ext.data.JsonReader({
            totalProperty : 'results',
            root : 'rows',
            fields : [{
                name : 'id'
            }, {
                name : 'descr'
            }, {
                name : 'layername',
                type : 'string'
            }]
        }),
        baseParams : {
            limit : 20,
            query : ""
        }
    });

    var sm_layer = new Ext.grid.CheckboxSelectionModel({
        handleMouseDown : Ext.emptyFn
    });
    var cm_layer = new Ext.grid.ColumnModel([
        // new Ext.grid.RowNumberer(),
        sm_layer, {
            header : '描述',
            dataIndex : 'descr',
            width : 65
        }, {
            header : '名称',
            dataIndex : 'layername',
            width : 140
        }]);

    // LayerPanel Toolbar
    var dateSelect = new Ext.form.DateField({
        fieldLabel : '日期',
        emptyText : '请选择',
        format : 'Y-m-d',
        value : '2009-10-20'
    });

    var layerBar = new Ext.Toolbar({
        items : [{
            xtype : 'tbspacer'
        }, dateSelect, {
            xtype : 'tbbutton',
            text : '查询',
            handler : function() {
                store_layer.baseParams = {
                    query : dateSelect.getValue()
                    .format('Y-m-d')
                };
                store_layer.load();
            }
        }]
    });

    // end of toolbar

    var grid_layer = new Ext.grid.GridPanel({
        height : 500,
        autoScroll : true,
        tbar : layerBar,
        cm : cm_layer,
        sm : sm_layer,
        store : store_layer
    });

    grid_layer.on('contextmenu', function(e) {
        e.preventDefault();
        menu_layer.showAt(e.getXY());
    })

    // == end of Layer Definition

    var combox = new Ext.form.ComboBox({
        emptyText : 'Select',
        mode : 'local',
        triggerAction : 'all',
        width : 130
    // transform: 'combo'
    });
    /*
	 * ! var set = new Ext.form.FieldSet({ width : 180, height : 320,
	 * columnWidth : 1, layout : 'column', border : true, anchor : '100%',
	 * labelWidth : 40, items : [{ columnWidth : 1, layout : 'form', border :
	 * false, items : [{ xtype : 'textfield', fieldLabel : 'aaaaa', name :
	 * 'aaaa', anchor : '95%' }, slider, combox] }] }); // Loop Control Form var
	 * loopForm = new Ext.FormPanel({ title : '简单查询', height : 400, width : 200,
	 * labelWidth : 50, // frame:true, // bodyStyle:'padding:3px 3px 0', //
	 * align : 'center' // defaults: {width: 100}, defaultType : 'textfield',
	 * tbar : ['<<', '<', 'S', 'P', '>', '>>'], items : [set], buttons : [{
	 * text : '按钮' }] });
	 * 
	 * var slider = new Ext.Slider({ width : 200, minValue : 0, maxValue : 100,
	 * plugins : new Ext.ux.SliderTip() });
	 * 
	 * 
	 * var infoTab = new Ext.TabPanel({ activeTab : 0, height : 150, plain :
	 * true, defaults : { autoScroll : true }, items : [{ title : 'Style',
	 * layout : 'fit', html : "My content was added during construction." //
	 * items: grid_bounds }, { title : '地理信息', autoLoad : 'ajax1.htm' }, { title :
	 * '基站信息', // autoLoad: {url: '/map/getbaseinfo', params: 'foo=bar&wtf=1'}
	 * layout : 'fit', items : grid_infoCell }, { title : '路测信息', // listeners:
	 * {activate: handleActivate}, html : "I am tab 4's content. I also have an
	 * event listener attached." }, { title : 'Disabled Tab', disabled : true,
	 * html : "Can't see me cause I'm disabled" }] });
	 */

    var treeBar = new Ext.Toolbar({
        cls : 'top-toolbar',
        items : [' ', new Ext.form.TextField({
            width : 180,
            emptyText : '输入基站名称',
            listeners : {
                render : function(f) {
                    f.el.on('keydown', filterTree, f, {
                        buffer : 350
                    });
                }
            }
        })]
    });

    var filter = new Ext.tree.TreeFilter(treePanel, {
        clearBlank : true,
        autoClear : true
    });

    var hiddenPkgs = [];

    function filterTree(e) {
        var text = e.target.value;
        Ext.each(hiddenPkgs, function(n) {
            n.ui.show();
        });

        if (!text) {
            filter.clear();
            return;
        }
        // treePanel.expandAll();

        var re = new RegExp(Ext.escapeRe(text), 'i');
        filter.filterBy(function(n) {
            return !n.isLeaf() || re.test(n.text);
        });

        // hide empty packages that weren't filtered
        hiddenPkgs = [];
        treePanel.root.cascade(function(n) {
            if (!n.isLeaf() && n.ui.ctNode.offsetHeight < 3) {
                n.ui.hide();
                hiddenPkgs.push(n);
            }
        });
    };

    treePanel.on('contextmenu', function(n, e) {
        e.preventDefault();
        menu1.showAt(e.getXY());
    })

    // View of all Layout
    viewport = new Ext.Viewport({
        layout : 'border',
        items : [new Ext.BoxComponent({
            region : 'north',
            el : 'north',
            height : 57
        }), {
            region : 'west',
            id : 'west-panel',
            // title: '*',
            split : true,
            width : 200,
            minSize : 175,
            maxSize : 400,
            collapsible : true,
            margins : '0 0 0 5',
            layout : 'accordion',
            collapseMode : 'mini',
            layoutConfig : {
                animate : true
            },
            items : [{
                title : '图层选择',
                enableDD : true,
                border : false,
                xtype : 'layertree',
                map : map,
                model : model
            }, {
                title : '基站浏览',
                Height : 550,
                autoScroll : true,
                tbar : treeBar,
                items : treePanel,
                border : false
            // },{
            // title: '图层设定',
            // items: grid_layer,
            // border: false
            }	, {
                title : '收藏管理',
                tbar : favorBar,
                items : treeFavor,
                border : false
            // },{ //item4
            // title: '控制',
            // items: loopForm,
            // border : false
            }]
        }, {
            region : 'center',
            layout : 'fit',
            xtype : 'mapcomponent',
            map : map,
            tbar : toolbar
        /*
							 * ! }, { // south panel // to be added information
							 * tabs region : 'south', split : true, layout :
							 * 'fit', collapsible : true, collapseMode : 'mini',
							 * collapsed : true, height : 150, items : infoTab }]
							 */

        }]
    });

    viewport.doLayout();
    initToolbarContent();

    // Ext.get('select_combo').select(0,false);

    // set up sliders
    var tsldsliders = tsldGetElementsByClass(tsldSliderClassName) // Find the
    // horizontal
    // sliders.
    for (var i = 0; i < tsldsliders.length; i++) {
        tsldsliders[i].onmousedown = slide; // Attach event listener.
    }
    var tslddisplays = tsldGetElementsByClass(tsldSliderDisplayClassName) // Find
    // the
    // displays.
    for (var i = 0; i < tslddisplays.length; i++) {
        tslddisplays[i].value = tslddisplays[i].defaultValue; // Resets
        // display on
        // page reload.
        tslddisplays[i].onfocus = focusDisplay; // Attach event listener.
    }

    // set up current map
    cur_map = 'green';

    map_tree = viewport.items['items'][1].items['items'][0];
    treeEditor = new Ext.tree.TreeEditor(map_tree, {
        allowBlank : false
    });

    map_tree.on("click", function(node, e) {
        /*
		 * store_field.baseParams = { feed: text }; store_field.load();
		 */
        // need change legend here
        var legend = document.getElementById('legend');
        var legendbg = document.getElementById('legendbg');
        if (node.text.indexOf("场强") >= 0 || node.text.indexOf("field") >= 0) {
            legend.style.visibility = 'visible';
            legendbg.style.visibility = 'visible';
            legend.src = '/images/legend_field.png';

        } else if (node.text.indexOf("话务") >= 0
            || node.text.indexOf("traffic") >= 0) {

            legend.style.visibility = 'visible';
            legendbg.style.visibility = 'visible';
            legend.src = '/images/legend_huawu.png';

            // 设置话务量计算的值
            if (node.text.indexOf("点") >= 0) {
                cur_time = 'val' + node.text.split("-")[1].split("点")[0];
            };

        } else {
            legend.src = '';
            legend.style.visibility = 'hidden';
            legendbg.style.visibility = 'hidden';
        }

        // change cur_map transdisplay
        for (var i = 0; i < model.length; i++) {
            for (var j = 0; j < model[i]["children"].length; j++) {
                text = model[i]["children"][j]["text"];
                if (text == node.text) {
                    cur_map = model[i]["children"][j]["layerNames"];
                    // change slide value
                    transval = document.getElementById('transdisplay');
                    val = 100 - map.getLayersByName(cur_map)[0].opacity * 100;
                    transval.setValue(val);
                    tsldLeft("stransslider", val);
                    break;
                }
            }
        }

    /*
			 * //change markWind infomation if (markWind != null) { var markProp =
			 * markWind.items['items'][0].items['items'][2].items['items'][0];
			 * var pars = "layername="+node.txt; new
			 * Ajax.Request("/map/mark_info", { method: "POST", parameters:
			 * pars, onComplete: function(request) { //msg ("Webgis", "任务添加成功！")
			 * markProp.setSource({ x : 100, y : 200, grid_id : 200000 }); } }); }
			 */

    }, map_tree);

    map_tree.on("contextmenu", function(node, e) {
        e.preventDefault();
        node.select();
        menu2.showAt(e.getXY());
    }, map_tree);

    map_tree.on("dragdrop", function() {
        map_tree._updateOrder();
        insert_layer("");
    }, map_tree);

    map_tree.addListener("checkchange", function checkChange(node, checked) {
        map_tree._handleModelChange(node, checked);
        insert_layer("");
    }, map_tree);

    // base_tree click handler
    var base_tree = viewport.items['items'][1].items['items'][1].items['items'][0];
    base_tree.on("click", function(node, checked) {
        panto_cellid(node.text);
        return false
    });

    // favor_tree click handler
    var favor_tree = viewport.items['items'][1].items['items'][2].items['items'][0];

    favor_tree.on("click", function(node, checked) {
        var pars = node.id.split("|"); // 0 : id , 1 : x, 2 : y, 3 :
        // zoom,
        // 4 : layers

        // set center and level
        var lonLat = new OpenLayers.LonLat(pars[1], pars[2]);
        map.setCenter(lonLat, pars[3]);

        // Delete 我的收藏的图层
        for (var k = 0; k < model[model.length - 1].children.length; k++) {
            var layer_name = model[model.length - 1].children[k].text;
            var mlayer = map.getLayersByName(layer_name)[0];
            map.removeLayer(mlayer);
        }

        // restore layers
        if (pars[4] != "") {
            var layers = pars[4].split(",");
            var new_node = {
                text : "我的收藏",
                checked : false,
                expanded : true,
                children : []
            };

            for (var k = layers.length - 1; k >= 0; k--) {
                var layer_name = layers[k].split(":")[0];
                var opacity = layers[k].split(":")[1];

                if (layer_name != 'gsat' && layer_name != 'geom_group')
                    new_node["children"][k] = {
                        text : layer_name,
                        checked : true,
                        layerName : layer_name
                    };

                // traffic1800_20100120_2:0.8 or traffic1800_2
                if (layer_name.indexOf('traffic') > 0
                    || layer_name.indexOf('field') > 0) {

                    var ss = layer_name.split("_");
                    if (ss.length == 3) {
                        var table = ss[0] + '_' + ss[1];
                        var key = ss[2];
                    } else {
                        table = ss[0];
                        key = ss[1];
                    }

                    var pars = "table=" + layer_name;
                    new Ajax.Request("/map/add_new_layer", {
                        method : "POST",
                        parameters : pars,
                        onComplete : function(request) {
                            var favor_layer = new OpenLayers.Layer.WMS(
                                layer_name, host_url, {
                                    layers : 'GZ125:'
                                    + layer_name,
                                    srs : 'EPSG:4326',
                                    transparent : true,
                                    format : format
                                }, {
                                    reproject : false,
                                    opacity : opacity,
                                    isBaseLayer : false
                                });
                            map.addLayers([favor_layer,
                                vectorLayer_9,
                                vectorLayer_18, markers]);
                        }
                    });

                } else

                // if the layers was not created, create it
                if (layer_name == 'gsat') {
                    map.setBaseLayer(geom_group);
                    map.setBaseLayer(gsat);
                    var lonLat = new OpenLayers.LonLat(pars[1], pars[2]);
                    map.setCenter(lonLat, pars[3]);
                } else if (layer_name == "geom_group") {
                    map.setBaseLayer(gsat);
                    map.setBaseLayer(geom_group);
                    var lonLat = new OpenLayers.LonLat(pars[1], pars[2]);
                    map.setCenter(lonLat, pars[3]);
                } else if (map.getLayersByName(layer_name).length == 0) {
                    var favor_layer = new OpenLayers.Layer.WMS(
                        layer_name, host_url, {
                            layers : 'GZ125:' + layer_name,
                            srs : 'EPSG:4326',
                            transparent : true,
                            format : format
                        }, {
                            reproject : false,
                            opacity : opacity,
                            isBaseLayer : false
                        });
                    map.addLayers([favor_layer, vectorLayer_9,
                        vectorLayer_18, markers]);
                } else {
                    var favor_layer = map.getLayersByName(layer_name)[0];
                    insert_layer(favor_layer);
                    favor_layer.setOpacity(opacity);
                    favor_layer.setVisibility(true);
                }
            };

            // var map_tree =
            // viewport.items['items'][1].items['items'][0];
            // var model = map_tree.model;
            model[model.length - 1] = new_node;
            var root = {
                text : 'Root',
                draggable : false, // disable root node dragging
                id : 'source',
                children : model,
                leaf : false
            };

            // Pre-build the tree so that non-expanded nodes exist in
            // the model.
            var rootNode = buildTree(root);
            map_tree.setRootNode(rootNode);
            map_tree._fixupModel();

            insert_layer("");
        // set active item
        // viewport.items["items"][1].getLayout().setActiveItem(0);
        }

        return false;
    });

    favor_tree.on("contextmenu", function(node, e) {
        e.preventDefault();
        node.select();
        menu_favor.showAt(e.getXY());
    });

    function refreshLog(msg) {
        var pnl = new Ext.Panel({
            autoScroll : true,
            bodyStyle : 'padding:5px',
            html : msg
        });

        var logBar = new Ext.Toolbar({
            items : [{
                xtype : 'tbspacer'
            }, {
                xtype : 'tbbutton',
                text : 'Clear',
                handler : function() {
                    pnl_html = '';
                    refreshLog(pnl_html);
                }
            }, {
                xtype : 'tbspacer'
            }, {
                xtype : 'tbbutton',
                text : 'Pause',
                handler : function() {
                    stopLog();
                }
            }]
        });

        if (logWind != null) {
            logWind.close();
        };

        logWind = new Ext.Window({
            title : 'Log 窗口',
            tbar : logBar,
            floating : true,
            shadow : true,
            draggable : true,
            collapsible : true,
            collapsed : true,
            closable : true,
            width : 400,
            height : 200,
            items : pnl,
            layout : 'fit',
            plain : true
        });
        logWind.show();
    }

    /*
	 * Log Check functions
	 */

    function startLog() {
        if (!logStart) {
            logStart = true;
            loopLog(logStart);
        }
    }

    function stopLog() {
        logStart = false;
    }

    function loopLog(lp) {

        pnl_html = 'Hello World' + '<br />' + pnl_html;
        refreshLog(pnl_html);

        if (lp) {
            var f = function() {
                loopLog(logStart)
            };
            var t = setTimeout(f, 5000);
        }
    }

    // menu design
    // right click menu for style
    var menu1 = new Ext.menu.Menu({
        items : [{
            text : '高亮显示'
        }, {
            text : '属性'
        }]
    });

    var menu_layer = new Ext.menu.Menu({
        items : [{
            text : '增加图层',
            handler : function(e) {
                menu_layer.hide();

                // Delete 我的收藏的图层
                for (var k = 0; k < model[model.length - 1].children.length; k++) {
                    var layer_name = model[model.length - 1].children[k].text;
                    var nlayer = map.getLayersByName(layer_name)[0];
                    map.removeLayer(nlayer);
                }

                // init new_mode
                var new_node = {
                    text : "我的图层",
                    checked : false,
                    expanded : true,
                    children : []
                };

                // Add 新的图层
                var selections = grid_layer.getSelectionModel().getSelections();
                for (var i = 0; i < selections.length; i++) {
                    var record = selections[i];
                    var layer_name = record.get("layername");
                    if (map.getLayersByName(layer_name).length == 0) {
                        var newlayer = new OpenLayers.Layer.WMS(layer_name,
                            host_url, {
                                layers : 'GZ125:' + layer_name,
                                srs : 'EPSG:4326',
                                transparent : true,
                                format : format
                            }, {
                                reproject : false,
                                opacity : 1,
                                isBaseLayer : false
                            });
                        insert_layer(newlayer);
                        new_node["children"][i] = {
                            text : layer_name,
                            checked : true,
                            layerName : layer_name
                        };
                    }
                } // end for

                // set model放在最后的新加图层里面
                model[model.length - 1] = new_node;
                var root = {
                    text : 'Root',
                    draggable : false, // disable root node dragging
                    id : 'source',
                    children : model,
                    leaf : false
                };

                // Pre-build the tree so that non-expanded nodes exist in the
                // model.
                var rootNode = buildTree(root);
                map_tree.setRootNode(rootNode);
                map_tree._fixupModel();

            // set active item
            // viewport.items["items"][1].getLayout().setActiveItem(0);

            }
        }, {
            text : '删除图层',
            handler : function(e) {
                menu_layer.hide();
                var selections = grid_layer.getSelectionModel().getSelections();
                for (var i = 0; i < selections.length; i++) {
                    var record = selections[i];
                    var layername = record.get("layername");
                    map.removeLayer(map.getLayersByName(layername)[0]);
                    for (var k = map.layers.length - 1; k >= 0; k--) {
                        if (map.layers[k].name == layername) {
                            map.removeLayer(map.layers[k]);
                            break;
                        }
                    }
                }

            }
        }, {
            text : '选定并播放动画图层',
            handler : function(e) {
                var selections = grid_layer.getSelectionModel().getSelections();
                if (totRadars > 0) {
                    for (var i = 0; i < totRadars; i++)
                        map.removeLayer(radars[i]);
                };

                radars = [];
                radnames = [];
                totRadars = selections.length;

                for (var i = 0; i < selections.length; i++) {
                    var record = selections[i];
                    var layername = record.get("layername");
                    radnames[i] = layername;
                    radars[i] = new OpenLayers.Layer.WMS('radar' + i, host_url,
                    {
                        layers : 'GZ125:' + layername,
                        srs : 'EPSG:4326',
                        transparent : true,
                        format : format
                    }, {
                        reproject : false,
                        opacity : 0,
                        isBaseLayer : false
                    });
                    insert_layer(radars[i]);
                }
                startRadar();
            }
        }, {
            text : '删除动画图层',
            handler : function(e) {
                if (totRadars > 0) {
                    for (var i = 0; i < totRadars; i++)
                        map.removeLayer(radars[i]);
                };

                radars = [];
                radnames = [];
                totRadars = 0;
                loopable = false;
            }
        }, {
            text : '启动动画',
            handler : function(e) {
                startRadar();
            }
        }, {
            text : '停止动画',
            handler : function(e) {
                stopRadar();
            }
        }]
    });

    var menu2 = new Ext.menu.Menu({
        items : [{
            text : '设置样式...',
            handler : function(node, e) {

                menu2.hide();

                var store_sld = new Ext.data.Store({
                    proxy : new Ext.data.HttpProxy({
                        url : '/map/getstyle'
                    }),

                    reader : new Ext.data.JsonReader({
                        totalProperty : 'results',
                        root : 'rows',
                        fields : [{
                            name : 'id'
                        }, {
                            name : 'cond',
                            type : 'string'
                        }, {
                            name : 'color',
                            type : 'string'
                        }]
                    })
                });

                var color_editor = new Ext.grid.GridEditor(new Ext.ux.ColorField(
                {
                    fieldLabel : 'Color',
                    id : 'color',
                    width : 175,
                    allowBlank : false
                }));
                var text_editor = new Ext.grid.GridEditor(new Ext.form.TextField());
                var grid_sld = new Ext.grid.EditorGridPanel({
                    store : store_sld,
                    clicksToEdit : 1,
                    columns : [{
                        id : 'id',
                        header : '编号',
                        width : 25,
                        sortable : true,
                        dataIndex : 'id'
                    }, {
                        header : '条件',
                        width : 75,
                        dataIndex : 'cond'
                    }, {
                        header : '颜色',
                        width : 80,
                        sortable : true,
                        renderer : formatColor,
                        dataIndex : 'color',
                        editor : color_editor
                    }],
                    stripeRows : true,
                    height : 300,
                    width : 200,
                    title : '-'
                });

                var stylePanel = new Ext.TabPanel({
                    xtype : "tabpanel",
                    activeTab : 0,
                    items : [{
                        xtype : "panel",
                        title : "场强SLD",
                        layout : "fit",
                        items : [{
                            layout : "border",
                            items : [{
                                region : "center",
                                title : "样式输出",
                                layout : "fit",
                                items : [{
                                    id : "outText",
                                    xtype : "textarea",
                                    fieldLabel : "Text",
                                    name : "textvalue"
                                }]
                            }, {
                                region : "south",
                                title : "",
                                height : 40,
                                split : false,
                                collapsible : false,
                                titleCollapse : false,
                                labelAlign : "'center'",
                                layout : "form",
                                items : [{
                                    xtype : 'form',
                                    text : "Hello",
                                    height : 30,
                                    items : [],
                                    buttons : [{
                                        text : '清除',
                                        handler : function() {
                                            Ext.get("outText").dom.value = "";
                                        }
                                    }, {
                                        text : '创建',
                                        handler : function() {
                                            // Ext.get("outText").dom.value
                                            // = "You are here!";
                                            var m = store_sld.data['items'];
                                            var jsonArray = [];
                                            Ext.each(m, function(item) {
                                                jsonArray
                                                .push(item.data);
                                            });

                                            var pars = "data="
                                            + encodeURIComponent(Ext
                                                .encode(jsonArray));
                                            // Ext.get("outText").dom.value
                                            // = pars;
                                            // Upload to Server
                                            new Ajax.Request(
                                                "/map/updateSLD", {
                                                    method : "POST",
                                                    parameters : pars,
                                                    onComplete : function(
                                                        request) {
                                                        var vals = eval("("
                                                            + request.responseText
                                                            + ")");
                                                        Ext
                                                        .get("outText").dom.value = vals;
                                                    }
                                                });
                                            return true;
                                        }
                                    }, {
                                        text : '应用',
                                        handler : function() {
                                            pars = ""
                                            new Ajax.Request(
                                                "/map/update_geoserver",
                                                {
                                                    method : "POST",
                                                    parameters : pars,
                                                    onComplete : function(
                                                        request) {
                                                        var vals = eval("("
                                                            + request.responseText
                                                            + ")");
                                                        if (vals == true)
                                                            Ext
                                                            .get("outText").dom.value = "更新样式表完成."
                                                    }
                                                });
                                            return true;
                                        }
                                    }]
                                }]
                            }, {
                                region : "west",
                                title : "颜色列表",
                                width : 180,
                                split : true,
                                layout : 'fit',
                                collapsible : true,
                                titleCollapse : true,
                                items : grid_sld
                            }]
                        }]
                    }, {
                        xtype : "panel",
                        title : "话务SLD"
                    }]
                });

                var styleWin = new Ext.Window({
                    title : '样式设置',
                    floating : true,
                    shadow : true,
                    draggable : true,
                    collapsible : true,
                    layout : 'fit',
                    width : 600,
                    height : 400,
                    autoScroll : true,
                    items : stylePanel
                });

                store_sld.load({
                    params : {
                        feed : "style_field"
                    }
                });
                styleWin.show();
            }
        }, {
            text : '新分类...',
            handler : function(node, e) {
                menu2.hide();
                var map_tree = viewport.items['items'][1].items['items'][0];
                var model = map_tree.model;

                model[model.length] = {
                    text : "新图层",
                    checked : false,
                    expanded : true,
                    children : []
                };

                var root = {
                    text : 'Root',
                    draggable : false, // disable root node dragging
                    id : 'source',
                    children : model,
                    leaf : false
                };

                var rootNode = buildTree(root);
                map_tree.setRootNode(rootNode);
                map_tree._fixupModel();

            }
        }/*
			 * , { text: '删除', handler: function(node,e){ menu2.hide();
			 * 
			 * var map_tree = viewport.items['items'][1].items['items'][0]; var
			 * model = map_tree.model; var node = map_tree.selModel.selNode;
			 * //update model before remove
			 * 
			 * node.remove(); map_tree._fixupModel();
			 * //map_tree.root.removeChild(node); } }
			 */
        ]
    });

    var menu_favor = new Ext.menu.Menu({
        items : [{
            text : '删除',
            handler : function(node, e) {
                menu_favor.hide();
                var node = favor_tree.selModel.selNode;
                var pars = "id=" + node.id;
                new Ajax.Request("/map/delfavor", {
                    method : "POST",
                    parameters : pars,
                    onComplete : function(request) {
                    }
                });
                node.remove();
            }
        }, {
            text : '刷新',
            handler : function(node, e) {
                menu_favor.hide();
                treeFavor.getRootNode().reload();
            }
        }]
    });

    pars = 'cur_date=now';
    new Ajax.Request("/map/set_cur_date", {
        method : 'POST',
        parameters : pars,
        onComplete : function(request) {

            new_date = request.responseText
            Ext.getCmp('select_combo').setValue(new_date.substr(1, 8));

            // delete all the layers
            delete_model_layers(model[2]);

            // set cur_date
            cur_date = new_date;

            // Add new layers
            opacity = 0.8;

            add_model_layer("border900" + cur_date, opacity);
            add_model_layer("field900" + cur_date, opacity);
            for (var k = 0; k < 26; k++)
                add_model_layer("traffic900" + cur_date + '_' + k,
                    opacity);
            add_model_layer("fan900" + cur_date, opacity);

            add_model_layer("border1800" + cur_date, opacity);
            add_model_layer("field1800" + cur_date, opacity);
            for (var k = 0; k < 26; k++)
                add_model_layer("traffic1800" + cur_date + '_' + k,
                    opacity);
            add_model_layer("fan1800" + cur_date, opacity);

            new_node = {
                text : '日期' + cur_date,
                checked : false,
                expanded : true,
                children : []
            };

            new_node["children"][0] = {
                text : 'GSM 900',
                checked : false,
                expanded : true,
                children : [{
                    text : "GSM900 边界",
                    checked : false,
                    layerName : "border900" + cur_date
                }, {
                    text : "GSM900 场强",
                    checked : false,
                    layerName : "field900" + cur_date
                }, {
                    text : "GSM900 话务",
                    checked : false,
                    expanded : false,
                    children : [{
                        text : "GSM900 话务-0点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_0"
                    }, {
                        text : "GSM900 话务-1点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_1"
                    }, {
                        text : "GSM900 话务-2点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_2"
                    }, {
                        text : "GSM900 话务-3点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_3"
                    }, {
                        text : "GSM900 话务-4点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_4"
                    }, {
                        text : "GSM900 话务-5点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_5"
                    }, {
                        text : "GSM900 话务-6点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_6"
                    }, {
                        text : "GSM900 话务-7点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_7"
                    }, {
                        text : "GSM900 话务-8点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_8"
                    }, {
                        text : "GSM900 话务-9点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_9"
                    }, {
                        text : "GSM900 话务-10点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_10"
                    }, {
                        text : "GSM900 话务-11点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_11"
                    }, {
                        text : "GSM900 话务-12点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_12"
                    }, {
                        text : "GSM900 话务-13点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_13"
                    }, {
                        text : "GSM900 话务-14点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_14"
                    }, {
                        text : "GSM900 话务-15点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_15"
                    }, {
                        text : "GSM900 话务-16点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_16"
                    }, {
                        text : "GSM900 话务-17点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_17"
                    }, {
                        text : "GSM900 话务-18点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_18"
                    }, {
                        text : "GSM900 话务-19点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_19"
                    }, {
                        text : "GSM900 话务-20点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_20"
                    }, {
                        text : "GSM900 话务-21点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_21"
                    }, {
                        text : "GSM900 话务-22点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_22"
                    }, {
                        text : "GSM900 话务-23点",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_23"
                    }, {
                        text : "GSM900 话务-上午",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_24"
                    }, {
                        text : "GSM900 话务-下午",
                        checked : false,
                        layerName : "traffic900" + cur_date
                        + "_25"
                    }]
                }, {
                    text : "GSM900 天线",
                    checked : false,
                    layerName : "fan900" + cur_date
                }]
            };

            new_node["children"][1] = {
                text : 'GSM 1800',
                checked : false,
                expanded : true,
                children : [{
                    text : "GSM1800 边界",
                    checked : false,
                    layerName : "border1800" + cur_date
                }, {
                    text : "GSM1800 场强",
                    checked : false,
                    layerName : "field1800" + cur_date
                }, {
                    text : "GSM1800 话务",
                    checked : false,
                    expanded : false,
                    children : [{
                        text : "GSM1800 话务-0点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_0"
                    }, {
                        text : "GSM1800 话务-1点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_1"
                    }, {
                        text : "GSM1800 话务-2点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_2"
                    }, {
                        text : "GSM1800 话务-3点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_3"
                    }, {
                        text : "GSM1800 话务-4点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_4"
                    }, {
                        text : "GSM1800 话务-5点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_5"
                    }, {
                        text : "GSM1800 话务-6点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_6"
                    }, {
                        text : "GSM1800 话务-7点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_7"
                    }, {
                        text : "GSM1800 话务-8点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_8"
                    }, {
                        text : "GSM1800 话务-9点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_9"
                    }, {
                        text : "GSM1800 话务-10点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_10"
                    }, {
                        text : "GSM1800 话务-11点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_11"
                    }, {
                        text : "GSM1800 话务-12点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_12"
                    }, {
                        text : "GSM1800 话务-13点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_13"
                    }, {
                        text : "GSM1800 话务-14点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_14"
                    }, {
                        text : "GSM1800 话务-15点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_15"
                    }, {
                        text : "GSM1800 话务-16点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_16"
                    }, {
                        text : "GSM1800 话务-17点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_17"
                    }, {
                        text : "GSM1800 话务-18点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_18"
                    }, {
                        text : "GSM1800 话务-19点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_19"
                    }, {
                        text : "GSM1800 话务-20点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_20"
                    }, {
                        text : "GSM1800 话务-21点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_21"
                    }, {
                        text : "GSM1800 话务-22点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_22"
                    }, {
                        text : "GSM1800 话务-23点",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_23"
                    }, {
                        text : "GSM1800 话务-上午",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_24"
                    }, {
                        text : "GSM1800 话务-下午",
                        checked : false,
                        layerName : "traffic1800" + cur_date
                        + "_25"
                    }]
                }, {
                    text : "GSM1800 天线",
                    checked : false,
                    layerName : "fan1800" + cur_date
                }]
            };

            model[2] = new_node;

            // reset model
            root = {
                text : 'Root',
                draggable : false, // disable root node dragging
                id : 'source',
                children : model,
                leaf : false
            };

            // Pre-build the tree so that non-expanded nodes exist in
            // the model.
            rootNode = buildTree(root);
            map_tree.setRootNode(rootNode);
            map_tree._fixupModel();

            insert_layer("");
        }

    });

});

// 飞行到中心点函数
function panto_id(id) {
    pars = "id=" + id;
    new Ajax.Request("/map/get_id", {
        method : "POST",
        parameters : pars,
        onComplete : function(request) {
            var vals = eval("(" + request.responseText + ")");
            var cell = vals[0]["user"];
            var lon = cell["lon"];
            var lat = cell["lat"];
            var lonlat = new OpenLayers.LonLat(lon, lat);
            map.panTo(lonlat, {
                animate : true
            });
        }
    });
    return false;
}

// 飞行到小区基站为中心点
function panto_cellid(text) {
    pars = "cellid=" + text;
    new Ajax.Request("/map/get_cellid", {
        method : "POST",
        parameters : pars,
        onComplete : function(request) {
            var vals = eval("(" + request.responseText + ")");
            var cell = vals[0]["user"];
            var lon = cell["lon"];
            var lat = cell["lat"];
            var lonlat = new OpenLayers.LonLat(lon, lat);
            map.panTo(lonlat);
        }
    });
    return false;
}

function panto_url(url, grid_id) {
    pars = "id=" + grid_id;
    new Ajax.Request(url, {
        method : "POST",
        parameters : pars,
        onComplete : function(request) {
            var vals = eval("(" + request.responseText + ")");
            var cell = vals[0]["user"];
            var lon = cell["lon"];
            var lat = cell["lat"];
            var lonlat = new OpenLayers.LonLat(lon, lat);
            map.panTo(lonlat);
        }
    });
    return false;
}

function toggleControl(element) {
    for (key in drawControls) {
        var control = drawControls[key];
        if (element.value == key && element.checked) {
            control.activate();
        } else {
            control.deactivate();
        }
    }

    for (key in measureControls) {
        control = measureControls[key];
        if (element.value == key && element.checked) {
            control.activate();
        } else {
            control.deactivate();
        }
    }
}

// for measurement
var prevPopup = null;
function clearMeasure() {
    if (prevPopup) {
        prevPopup.close();
    }
    prevPopup = null
}

function createPopup(value) {
    clearMeasure();
    var html = value;
    var popup = new Ext.Window({
        title : '测量结果-' + cur_time,
        html : html,
        width : 200,
        bodyStyle : 'background-color:#FFFFD0;'
    });
    prevPopup = popup;
    popup.show();
}

/**
 * cell_ds : Cells dataStore 天线属性窗口的布局图
 * 
 */
var store_bounds = new Ext.data.Store({
    proxy : new Ext.data.HttpProxy({
        url : '/map/getboundcells'
    }),
    reader : new Ext.data.JsonReader({
        totalProperty : 'results',
        root : 'rows',
        fields : [{
            name : 'id'
        }, {
            name : 'cell_id',
            type : 'string'
        }, {
            name : 'basename',
            type : 'string'
        }, {
            name : 'addr',
            type : 'string'
        }, {
            name : 'height',
            type : 'string'
        }, {
            name : 'delta',
            type : 'string'
        }, {
            name : 'build_height',
            type : 'string'
        }]
    })

});

var cm_bounds = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
    header : '编号',
    dataIndex : 'id',
    width : 40,
    sortable : true
}, {
    header : '基站名',
    dataIndex : 'cell_id',
    width : 80,
    sortable : true
}, {
    header : '基站中文名',
    dataIndex : 'basename',
    width : 100,
    sortable : true
}, {
    header : '地址',
    dataIndex : 'addr',
    width : 150,
    sortable : true
}, {
    header : '高度',
    dataIndex : 'height',
    width : 40,
    sortable : true
}, {
    header : '楼差',
    dataIndex : 'delta',
    width : 40,
    sortable : true,
    renderer : renderDelta
}, {
    header : '楼高',
    dataIndex : 'build_height',
    width : 40,
    sortable : true
}]);

var grid_bounds = new Ext.grid.GridPanel({
    store : store_bounds,
    cm : cm_bounds,
    stripeRows : true,
    height : 330,
    width : 400,
    plain : true
});

function renderDelta(value) {
    if (parseFloat(value) < 0) {
        return "<span style='color:red;font-weight:bold;'>" + value + "</span>";
    } else {
        return value;
    }
}

grid_bounds.on("rowclick", function(grid, rowIndex, e) {
    var row = grid.store.getAt(rowIndex);
    panto_id(row.data["id"]);
});

var cellGrid = new Ext.Window({
    title : 'Cells 列表',
    floating : true,
    shadow : true,
    draggable : true,
    collapsible : true,
    collapsed : true,
    closeAction : 'hide',
    layout : 'fit',
    width : 560,
    height : 400,
    autoScroll : true,
    plain : true,
    x : 700,
    y : 50,
    items : grid_bounds
});

cellGrid.hide();

// For Info Bar
/**
 * cell_ds : Cells dataStore 天线属性窗口的布局图
 * 
 */
// id, x(geom) as lon, y(geom) as lat, direction, bcchno, celltype, cell_id,
// base_name, addr, height
var store_infoCell = new Ext.data.Store({
    proxy : new Ext.data.HttpProxy({
        url : '/map/getInfoCell'
    }),
    reader : new Ext.data.JsonReader({
        totalProperty : 'results',
        root : 'rows',
        fields : [{
            name : 'id'
        }, {
            name : 'cell_id',
            type : 'string'
        }, {
            name : 'basename',
            type : 'string'
        }, {
            name : 'addr',
            type : 'string'
        }, {
            name : 'height',
            type : 'string'
        }, {
            name : 'direction',
            type : 'string'
        }, {
            name : 'bcchno',
            type : 'string'
        }]
    })
});

var cm_infoCell = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
    header : '编号',
    dataIndex : 'id',
    width : 40,
    sortable : true
}, {
    header : '基站名',
    dataIndex : 'cell_id',
    width : 80,
    sortable : true
}, {
    header : '基站中文名',
    dataIndex : 'basename',
    width : 100,
    sortable : true
}, {
    header : '地址',
    dataIndex : 'addr',
    width : 150,
    sortable : true
}, {
    header : '高度',
    dataIndex : 'height',
    width : 40,
    sortable : true
}, {
    header : '方向',
    dataIndex : 'direction',
    width : 40,
    sortable : true
}, {
    header : 'bcchno',
    dataIndex : 'bcchno',
    width : 40,
    sortable : true
}]);

var grid_infoCell = new Ext.grid.GridPanel({
    store : store_infoCell,
    cm : cm_infoCell,
    stripeRows : true,
    height : 330,
    width : 600,
    plain : true
});

function renderDelta(value) {
    if (parseFloat(value) < 0) {
        return "<span style='color:red;font-weight:bold;'>" + value + "</span>";
    } else {
        return value;
    }
}

grid_infoCell.on("rowclick", function(grid, rowIndex, e) {
    var row = grid.store.getAt(rowIndex);
    panto_id(row.data["id"]);
});

// End of Infor Bar

/**
 * Function: renderMoveCell() 用来更新当前BBox里面的天线数据，存放到cell_ds
 */
function renderMoveCell(event) {
    function calcVincenty(geometry) {
        var dist = 0;
        for (var i = 1; i < geometry.components.length; i++) {
            var first = geometry.components[i - 1];
            var second = geometry.components[i];
            dist += OpenLayers.Util.distVincenty({
                lon : first.x,
                lat : first.y
            }, {
                lon : second.x,
                lat : second.y
            });
        }
        return dist;
    }

    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var out = "";

    // show cellGrid float Window
    if (showFans) {
        pars = "(";
        points = geometry.components[0];

        for (var i = 0; i < points.components.length - 1; i++) {
            var pt = points.components[i];
            pars = pars + pt.x + ' ' + pt.y + ',';
        }

        var pt = points.components[0];
        pars = pars + pt.x + ' ' + pt.y + ')';
        var cell_bounds = pars;
        cellGrid.show();
        if (cellGrid.collapsed)
            cellGrid.expand(true);
        store_bounds.load({
            params : {
                bounds : pars
            }
        });
    } else {

        if (order == 1) {
            out += measure.toFixed(3) + " " + units;
            createPopup(out);
            return;
        } else {
            out += "面积:" + measure.toFixed(3) + " " + units + "<sup>2</sup>";
        }
        createPopup(out);

        var bounds = "(";
        var points = geometry.components[0];

        for (var i = 0; i < points.components.length - 1; i++) {
            var pt = points.components[i];
            bounds = bounds + pt.x + ' ' + pt.y + ',';
        }

        var pt = points.components[0];
        bounds = bounds + pt.x + ' ' + pt.y + ')';

        pars = {
            bounds : bounds,
            cur_time : cur_time
        };
        new Ajax.Request("/map/geterl9", {
            method : "POST",
            parameters : pars,
            onComplete : function(request) {

                places = eval("(" + request.responseText + ")");

                if (request.responseText.length > 10) {
                    place = places[0];
                    erl = parseFloat(place["user"]["sum"]);
                    if (isNaN(erl))
                        erl = 0;
                    var hw_str = erl.toFixed(5);
                    out += '<br>' + '900话务量: ' + hw_str;
                    createPopup(out);
                }
            }
        });

        new Ajax.Request("/map/geterl18", {
            method : "POST",
            parameters : pars,
            onComplete : function(request) {

                places = eval("(" + request.responseText + ")");

                if (request.responseText.length > 10) {
                    place = places[0];
                    erl = parseFloat(place["user"]["sum"]);
                    if (isNaN(erl))
                        erl = 0;
                    hw_str = erl.toFixed(5);
                    out += '<br>' + '1800话务量: ' + hw_str;
                    createPopup(out);
                }
            }
        });
    }
}

function renderMeasure(event) {
    function calcVincenty(geometry) {
        var dist = 0;
        for (var i = 1; i < geometry.components.length; i++) {
            var first = geometry.components[i - 1];
            var second = geometry.components[i];
            dist += OpenLayers.Util.distVincenty({
                lon : first.x,
                lat : first.y
            }, {
                lon : second.x,
                lat : second.y
            });
        }
        return dist;
    }

    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var out = "";

    if (order == 1) {
        out += measure.toFixed(3) + " " + units;
        if (map.getProjection() == "EPSG:4326") {
            out += '<br /	 > ';
            out += '<a href="';
            out += OpenLayers.i18n('http://en.wikipedia.org/wiki/Great_circle');
            out += '"target = "_blank" > ';
            out += OpenLayers.i18n('Great Circle Distance');
            out += '</a>:';
            out += calcVincenty(geometry).toFixed(3) + " km";
        }
    } else {
        out += "面积:" + measure.toFixed(3) + " " + units + "<sup>2</sup>";
    }
    createPopup(out);

    pars = "bounds=(";
    points = geometry.components[0];

    for (var i = 0; i < points.components.length - 1; i++) {
        pt = points.components[i];
        pars = pars + pt.x + ' ' + pt.y + ',';
    }

    pt = points.components[0];
    pars = pars + pt.x + ' ' + pt.y + ')';

    new Ajax.Request("/map/geterl9", {
        method : "POST",
        parameters : pars,
        onComplete : function(request) {

            places = eval("(" + request.responseText + ")");

            if (request.responseText.length > 10) {
                place = places[0];
                erl = parseFloat(place["user"]["sum"]);
                if (isNaN(erl))
                    erl = 0;
                hw_str = erl.toFixed(5);
                out += '<br>' + '900话务量: ' + hw_str;
                createPopup(out);
            }
        }
    });

    new Ajax.Request("/map/geterl18", {
        method : "POST",
        parameters : pars,
        onComplete : function(request) {

            places = eval("(" + request.responseText + ")");

            if (request.responseText.length > 10) {
                place = places[0];
                var erl = parseFloat(place["user"]["sum"]);
                if (isNaN(erl))
                    erl = 0;
                var hw_str = erl.toFixed(5);
                out += '<br>' + '1800话务量: ' + hw_str;
                createPopup(out);
            }
        }
    });
}

// for measurements
function stylemap() {
    var sketchSymbolizers = {
        "Point" : {
            pointRadius : 4,
            graphicName : "square",
            fillColor : "white",
            fillOpacity : 1,
            strokeWidth : 1,
            strokeOpacity : 1,
            strokeColor : "#FF0000"
        },
        "Line" : {
            strokeWidth : 3,
            strokeOpacity : 1,
            strokeColor : "#FFFF00"
        },
        "Polygon" : {
            strokeWidth : 2,
            strokeOpacity : 1,
            strokeColor : "#FFFF00",
            fillColor : "white",
            fillOpacity : 0.3
        }
    };

    var style = new OpenLayers.Style();
    style.addRules([new OpenLayers.Rule({
        symbolizer : sketchSymbolizers
    })]);
    var styleMap = new OpenLayers.StyleMap({
        "default" : style
    });

    return styleMap;
}

var h_options = {
    handlerOptions : {
        style : "default",
        layerOptions : {
            styleMap : stylemap()
        },
        persist : true
    },
    eventListeners : {
        'measure' : renderMoveCell,
        'measurepartial' : clearMeasure,
        'deactivate' : clearMeasure
    }
};

function getPointCalculator() {
    return new OpenLayers.Control.Measure(OpenLayers.Handler.Point, h_options);
}

function getLengthCalculator() {
    return new OpenLayers.Control.Measure(OpenLayers.Handler.Path, h_options);
}

function getAreaCalculator() {
    return new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon, h_options);
}

function addSeparator(toolbar) {
    toolbar.add(new Ext.Toolbar.Spacer());
    toolbar.add(new Ext.Toolbar.Separator());
    toolbar.add(new Ext.Toolbar.Spacer());
}

// test

// Ext.onReady(function() {
/*
 * ! var test_store = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url :
 * '/map/gettest' }),
 * 
 * reader : new Ext.data.JsonReader({ totalProperty : 'results', root : 'rows',
 * fields : [{ name : 'id', type : 'string' }, { name : 'cell_id', type :
 * 'string' }, { name : 'basename', type : 'string' }] }), baseParams : { limit :
 * 15, query : " " } });
 * 
 * var test_cm = new Ext.grid.ColumnModel({ columns : [new
 * Ext.grid.RowNumberer(), { header : '编号', dataIndex : 'id', width : 60 }, {
 * header : '基站ID', dataIndex : 'cell_id', width : 80 }, { header : '基站名称',
 * dataIndex : 'basename', width : 200 }], defaults : { sortable : true,
 * menuDisabled : true // forceFit : true // autofill : true } });
 * 
 * var test_grid = new Ext.grid.GridPanel({ // title:'Forum Search', store :
 * test_store, // layout : 'fit', // resizable: true, // width: 400, height :
 * 440, // autofill : true, // autoScroll : true,
 * 
 * tbar : ['搜索: ', '', new Ext.ux.form.SearchField({ store : test_store, //
 * height : 50, width : 260 })],
 * 
 * cm : test_cm,
 * 
 * bbar : new Ext.PagingToolbar({ store : test_store, pageSize : 15, displayInfo :
 * true, displayMsg : ' {0} - {1} of {2}', emptyMsg : "没有找到！" // prependButtons:
 * true }) });
 * 
 * var test_win = new Ext.Window({ title : 'cell查询定位', floating : true, shadow :
 * true, draggable : true, collapsible : true, collapsed : true, closeAction :
 * 'hide', // layout: 'fit', // resizable: true, width : 420, height : 490,
 * autofill : true, autoScroll : true, plain : true, x : 220, y : 80, items :
 * test_grid });
 * 
 * test_store.load({ params : { start : 0, limit : 15 } });
 * 
 * test_win.show();
 */
// });
// Search Cell Store
// Ext.onReady(function(){
var store_cell = new Ext.data.Store({
    proxy : new Ext.data.HttpProxy({
        url : '/map/getCellStore'
    }),

    reader : new Ext.data.JsonReader({
        totalProperty : 'results',
        root : 'rows',
        fields : [{
            name : 'id',
            type : 'string'
        }, {
            name : 'cell_id',
            type : 'string'
        }, {
            name : 'basename',
            type : 'string'
        }]
    }),
    baseParams : {
        limit : 15,
        query : ""
    }
});

var cm_cell = new Ext.grid.ColumnModel({
    columns : [new Ext.grid.RowNumberer(), {
        header : '编号',
        dataIndex : 'id',
        width : 60
    }, {
        header : '基站ID',
        dataIndex : 'cell_id',
        width : 80
    }, {
        header : '基站名称',
        dataIndex : 'basename',
        width : 200
    }],
    defaults : {
        sortable : true,
        menuDisabled : true
    // forceFit : true
    // autofill : true
    }
});

var grid_cell = new Ext.grid.GridPanel({
    // title:'Forum Search',
    store : store_cell,
    // layout : 'fit',
    // resizable: true,
    // width: 400,
    // height:440,
    // autofill : true,
    // autoScroll : true,

    tbar : ['搜索: ', '', new Ext.ux.form.SearchField({
        id : 'shao',
        store : store_cell,
        xtype: 'twintriggerfield',
        // height : 50,
        width : 260
    })],

    cm : cm_cell,

    bbar : new Ext.PagingToolbar({
        store : store_cell,
        pageSize : 15,
        displayInfo : true,
        displayMsg : ' {0} - {1} of {2}',
        emptyMsg : "没有找到！"
    // prependButtons: true
    })
});

grid_cell.on("rowclick", function(grid, rowIndex, e) {
    var row = grid.store.getAt(rowIndex);
    panto_id(row.data["id"]);
});

var cellwin = new Ext.Window({
    title : 'cell查询定位',
    floating : true,
    shadow : true,
    draggable : true,
    collapsible : true,
    collapsed : true,
    closeAction : 'hide',
    // layout: 'fit',
    // resizable: true,
    width : 420,
    // height: 490,
    autofill : true,
    autoScroll : true,
    plain : true,
    x : 220,
    y : 80,
    items : grid_cell
});



var showSearch = function() {
    // store_cell.load({params:{}});
    cellwin.show();
    Ext.fly('shao').up('div').setWidth(300,true);


}

var favorite_form = new Ext.form.FormPanel({
    labelAlign : 'right',
    labelWidth : 100,
    frame : true,
    // trackResetOnLoad : true,
    defaultType : 'textfield',
    items : [{
        fieldLabel : '保存名称',
        name : 'name',
        emptyText : '请输入名称',
        allowBlank : false
    }, {
        fieldLabel : '中心位置',
        name : 'boundary'
    }, {
        fieldLabel : '图层',
        name : 'layers'
    }, {
        fieldLabel : '缩放级别',
        name : 'level'
    }, {
        fieldLabel : '日期',
        name : 'date'
    }]

});

var favorite_win = new Ext.Window({
    title : '收藏地图',
    floating : true,
    shadow : true,
    draggable : true,
    collapsible : true,
    collapsed : true,
    closeAction : 'hide',
    layout : 'fit',
    width : 320,
    height : 215,
    autoScroll : true,
    plain : true,
    x : 420,
    y : 180,
    // buttonAlign : 'center',
    items : favorite_form,
    buttons : [{
        text : '确定',
        handler : function() {
            vals = favorite_form.getForm().getValues();
            pars = "savename=" + vals.name + "&boundary="
            + vals.boundary + "&layers=" + vals.layers
            + "&level=" + vals.level + "&date=" + vals.date;
            new Ajax.Request("/map/addFavorite", {
                method : "POST",
                parameters : pars,
                onComplete : function(request) {
                // treeFavor.getRootNode().reload();
                }
            });
            favorite_win.hide();
        }
    }, {
        text : '取消',
        handler : function() {
            favorite_win.hide();
        }
    }]
});

var showFavorite = function() {
    // basic.findField("name").setValue("123456");
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1
    var day = currentTime.getDate()
    var year = currentTime.getFullYear()

    // layers
    var layers = '';
    for (var k = map.layers.length - 1; k >= 0; k--) {
        if (map.layers[k].visibility) {
            if (map.layers[k].name.indexOf('vector') < 0
                && map.layers[k].name.indexOf('Markers') < 0
                && map.layers[k].name.indexOf('Graticule') < 0) {
                if (layers == '')
                    layers = map.layers[k].name + ':' + map.layers[k].opacity
                else
                    layers = layers + ',' + map.layers[k].name + ':'
                    + map.layers[k].opacity;
            }
        }
    }

    favorite_win.show();
    favorite_form.getForm().setValues({
        layers : layers,
        level : map.zoom + '',
        boundary : parseInt(map.center.lon) + ','
        + parseInt(map.center.lat),
        date : year + "-" + month + "-" + day
    });
}

/**
 * wizard grid definition
 * 
 */

var wiz_data = [['*', '全部'], ['GSM900', 'GSM 900'], ['GSM1800', 'GSM 1800']];

var wiz_store = new Ext.data.SimpleStore({
    fields : ['value', 'text'],
    data : wiz_data
});

var wiz_store2 = new Ext.data.Store({
    proxy : new Ext.data.HttpProxy({
        url : '/map/getLayerStore2'
    }),
    reader : new Ext.data.JsonReader({
        totalProperty : 'results',
        root : 'rows',
        fields : [{
            name : 'id'
        }, {
            name : 'descr'
        }, {
            name : 'layername',
            type : 'string'
        }, {
            name : 'create_at'
        }]
    }),
    pruneModifiedRecords : true,
    baseParams : {
        limit : 10,
        query : ""
    }
});

var wiz_selmodel = new Ext.grid.CheckboxSelectionModel({
    handleMouseDown : Ext.emptyFn
});
var wiz_colmodel = new Ext.grid.ColumnModel([wiz_selmodel, {
    header : '描述',
    dataIndex : 'descr',
    width : 65
}, {
    header : '名称',
    dataIndex : 'layername',
    width : 140
}, {
    header : '日期',
    dataIndex : 'create_at',
    width : 140
}]);

/**
 * Interactive Operation grid definition
 * 
 * @oper_grid
 * 
 */
var oper_store = new Ext.data.Store({
    proxy : new Ext.data.HttpProxy({
        url : '/map/getOperStore'
    }),
    reader : new Ext.data.JsonReader({
        totalProperty : 'results',
        root : 'rows',
        fields : [{
            name : 'id'
        }, {
            name : 'oper_id'
        }, {
            name : 'operate'
        }, {
            name : 'cell_id'
        }, {
            name : 'basename'
        }, {
            name : 'height'
        }, {
            name : 'direction'
        }, {
            name : 'vangle'
        }, {
            name : 'bspwrb'
        }, {
            name : 'grid_id'
        }, {
            name : 'lon'
        }, {
            name : 'lat'
        }]
    }),
    pruneModifiedRecords : true,
    baseParams : {
        limit : 10,
        query : ""
    }
});

var oper_selmodel = new Ext.grid.CheckboxSelectionModel({
    handleMouseDown : Ext.emptyFn
});
var oper_colmodel = new Ext.grid.ColumnModel([oper_selmodel, {
    header : 'id',
    dataIndex : 'oper_id',
    width : 25
}, {
    header : '操作',
    dataIndex : 'operate',
    width : 40
}, {
    header : 'cell',
    dataIndex : 'cell_id',
    width : 80
}, {
    header : 'basename',
    dataIndex : 'basename',
    width : 100
}, {
    header : '方向',
    dataIndex : 'direction',
    width : 40
}, {
    header : '下倾角',
    dataIndex : 'vangle',
    width : 40
}, {
    header : '高度',
    dataIndex : 'height',
    width : 40
}, {
    header : '功率',
    dataIndex : 'bspwrb',
    width : 40
}, {
    header : 'lon',
    dataIndex : 'lon',
    width : 80
}, {
    header : 'lat',
    dataIndex : 'lat',
    width : 80
}]);

var oper_layer = new Ext.grid.GridPanel({
    id : 'wiz_panel',
    height : 180,
    autoScroll : true,
    cm : oper_colmodel,
    sm : oper_selmodel,
    store : oper_store
});

var oper_win = new Ext.Window({
    title : '交互计算',
    floating : true,
    shadow : true,
    draggable : true,
    closeAction : 'hide',
    width : 650,
    height : 360,
    x : 340,
    y : 158,
    items : [oper_layer],
    buttons : [{
        text : '删除',
        handler : function() {

            selections = oper_layer.getSelectionModel().getSelections();
            pars = "id="
            for (var i = 0; i < selections.length; i++) {
                var record = selections[i];
                pars += record.get("id") + ',';
            }

            new Ajax.Request("/map/delOperate", {
                method : "POST",
                parameters : pars,
                onComplete : function(request) {
                    oper_store.load();
                }
            });
        }
    }, {
        text : '确定'
    }],
    layout : 'fit',
    plain : true
});

/**
 * Toolbar definition
 * 
 */
function initToolbarContent() {

    toolbar.addControl(new OpenLayers.Control.ZoomToMaxExtent({
        map : map,
        title : '全景区域'
    }), {
        iconCls : 'zoomfull',
        toggleGroup : 'map'
    });

    addSeparator(toolbar);

    toolbar.addControl(new OpenLayers.Control.ZoomBox({
        title : '放大区域'
    }), {
        iconCls : 'zoomin',
        toggleGroup : 'map'
    });

    toolbar.addControl(new OpenLayers.Control.ZoomBox({
        out : true,
        title : '缩小区域'
    }), {
        iconCls : 'zoomout',
        toggleGroup : 'map'
    });

    toolbar.addControl(new OpenLayers.Control.DragPan({
        isDefault : true,
        title : '拖动地图'
    }), {
        iconCls : 'pan',
        toggleGroup : 'map'
    });

    addSeparator(toolbar);

    toolbar.addControl(getLengthCalculator(), {
        iconCls : 'drawline',
        tooltip : '测量距离',
        toggleGroup : 'map '
    });

    toolbar.addControl(getAreaCalculator(), {
        iconCls : 'drawpolygon',
        tooltip : '测量面积及话务量',
        toggleGroup : 'map '
    });

    addSeparator(toolbar);

    // histroy
    var nav = new OpenLayers.Control.NavigationHistory();
    map.addControl(nav);
    nav.activate();

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'back',
        tooltip : '前一幅地图',
        handler : nav.previous.trigger
    }));

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'next',
        tooltip : '下一幅地图',
        handler : nav.next.trigger
    }));

    addSeparator(toolbar);

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'wizard',
        tooltip : '增加图层向导',
        handler : function() {

            var wiz_layer = new Ext.grid.GridPanel({
                id : 'wiz_panel',
                height : 180,
                autoScroll : true,
                cm : wiz_colmodel,
                sm : wiz_selmodel,
                store : wiz_store2
            })

            var wizard = new Ext.ux.Wiz({

                title : '添加图层向导',

                headerConfig : {
                    title : '添加地图'
                },

                cardPanelConfig : {
                    defaults : {
                        baseCls : 'x-small-editor',
                        bodyStyle : 'padding:40px 15px 5px 120px;background-color:#F6F6F6;',
                        border : false
                    }
                },

                cards : [

                // first card with welcome message
                new Ext.ux.Wiz.Card({
                    title : '欢迎',
                    items : [{
                        border : false,
                        bodyStyle : 'background:none;',
                        html : '欢迎使用图层增加向导, 请先选择图层类型、开始、结束时间，然后再设定添加类型.'
                    + '在操作过程中，可以按Canel退出.'
                    + '<br/><br/>'
                    + '请按next继续，并选择相应的数值.'
                    }]
                }),

                // second card with input fields last/firstname
                new Ext.ux.Wiz.Card({
                    title : '参数选择',
                    monitorValid : true,
                    defaults : {
                        labelStyle : 'font-size:11px'
                    },
                    items : [{
                        xtype : "fieldset",
                        title : "查询参数",
                        autoHeight : true,
                        layout : "form",
                        items : [{
                            border : false,
                            bodyStyle : 'background:none;padding-bottom:30px;',
                            html : '请选择查询的类型，开始和结束时间.'
                        }, {
                            xtype : "combo",
                            fieldLabel : "查询类型",
                            name : "wiz_type",
                            hiddenName : "wiz",
                            store : wiz_store,
                            emptyText : "请选择",
                            mode : 'local',
                            triggerAction : 'all',
                            valueField : 'value',
                            displayField : 'text',
                            width : 150,
                            allowBlank : false,
                            value : '*',
                            readOnly : true
                        }, {
                            xtype : "datefield",
                            fieldLabel : "开始时间",
                            name : "datevalue1",
                            format : "Y-m-d",
                            allowBlank : false,
                            width : 150
                        // value : getDiffDate(-30)
                        }, {
                            xtype : "datefield",
                            fieldLabel : "结束时间",
                            allowBlank : false,
                            name : "datevalue2",
                            format : "Y-m-d",
                            width : 150
                        // value : getDiffDate(0)
                        }, {
                            border : false,
                            bodyStyle : 'background:none;padding-bottom:20px;',
                            html : ''
                        }]
                    }]
                }),

                // third card with input field email-address
                new Ext.ux.Wiz.Card({
                    title : '图层选择',
                    monitorValid : true,
                    defaults : {
                        labelStyle : 'font-size:11px'
                    },
                    items : [{
                        border : false,
                        bodyStyle : 'background:none;padding-bottom:10px;',
                        html : '请选择图层:'
                    }, wiz_layer]
                }),

                // fourth card with finish-message
                new Ext.ux.Wiz.Card({
                    title : '结束',
                    monitorValid : true,
                    items : [{
                        border : false,
                        bodyStyle : 'background:none;',
                        items : [{
                            border : false,
                            bodyStyle : 'background:none;padding-bottom:10px;',
                            html : '请选择操模式:'
                        }, {
                            xtype : 'fieldset',
                            title : '-',
                            autoheight : true,
                            defaultType : 'radio',
                            items : [{
                                boxLabel : '添加到图层选择',
                                name : 'radio',
                                inputValue : '1',
                                checked : true
                            }, {
                                boxLabel : '作为动画图层添加',
                                name : 'radio',
                                inputValue : '2',
                                checked : false
                            }]
                        }]
                    }]
                })]
            });
            wizard.on("finish", function(e, data) {

                var mode = this.cards[3].form.findField('radio')
                .getGroupValue();
                var map_tree = viewport.items['items'][1].items['items'][0];
                var model = map_tree.model;

                if (mode == 1) { // stardard mode

                    // Delete 我的收藏的图层
                    for (var k = 0; k < model[model.length - 1].children.length; k++) {
                        var layer_name = model[model.length - 1].children[k].text;
                        var olayer = map.getLayersByName(layer_name)[0];
                        map.removeLayer(olayer);
                    }

                    // init new_mode
                    var new_node = {
                        text : "我的图层",
                        checked : false,
                        expanded : true,
                        children : []
                    };

                    // Add 新的图层
                    var selections = wiz_layer.getSelectionModel()
                    .getSelections();
                    for (var i = 0; i < selections.length; i++) {
                        var record = selections[i];
                        var layer_name = record.get("layername");
                        if (map.getLayersByName(layer_name).length == 0) {
                            var newlayer = new OpenLayers.Layer.WMS(layer_name,
                                host_url, {
                                    layers : 'GZ125:' + layer_name,
                                    srs : 'EPSG:4326',
                                    transparent : true,
                                    format : format
                                }, {
                                    reproject : false,
                                    opacity : 1,
                                    isBaseLayer : false
                                });
                            insert_layer(newlayer);
                            new_node["children"][i] = {
                                text : layer_name,
                                checked : true,
                                layerName : layer_name
                            };
                        }
                    } // end for

                    // set model放在最后的新加图层里面
                    model[model.length - 1] = new_node;
                    var root = {
                        text : 'Root',
                        draggable : false, // disable root node
                        // dragging
                        id : 'source',
                        children : model,
                        leaf : false
                    };

                    // Pre-build the tree so that non-expanded nodes
                    // exist in the model.
                    var rootNode = buildTree(root);
                    map_tree.setRootNode(rootNode);
                    map_tree._fixupModel();

                } else if (mode == 2) { // radar mode
                    var selections = wiz_layer.getSelectionModel()
                    .getSelections();
                    if (totRadars > 0) {
                        for (var i = 0; i < totRadars; i++)
                            map.removeLayer(radars[i]);
                    };

                    radars = [];
                    radnames = [];
                    totRadars = selections.length;

                    for (var i = 0; i < selections.length; i++) {
                        var record = selections[i];
                        var layername = record.get("layername");
                        radnames[i] = layername;
                        radars[i] = new OpenLayers.Layer.WMS('radar' + i,
                            host_url, {
                                layers : 'GZ125:' + layername,
                                srs : 'EPSG:4326',
                                transparent : true,
                                format : format
                            }, {
                                reproject : false,
                                opacity : 0,
                                isBaseLayer : false
                            });
                        insert_layer(radars[i]);
                    }
                    startRadar();
                }
            });

            wizard.on("next", function(e, data) {
                if (wizard.currentCard == 1) {
                    var types = this.cards[1].form.findField('wiz')
                    .getValue();
                    var date1 = this.cards[1].form
                    .findField('datevalue1').getValue()
                    .format('Y-m-d');
                    var date2 = this.cards[1].form
                    .findField('datevalue2').getValue()
                    .format('Y-m-d');
                    wiz_store2.baseParams = {
                        query : types + ',' + date1 + ',' + date2
                    };
                    wiz_store2.load();
                }
            });
            // show the wizard
            wizard.show();
        }
    }));

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'search',
        tooltip : 'cell查询定位',
        handler : showSearch
    }));

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'favorite',
        tooltip : '收藏',
        handler : showFavorite
    }));

    addSeparator(toolbar);

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'pause',
        tooltip : '暂停动画',
        handler : stopRadar
    }));

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'play',
        tooltip : '播放动画',
        handler : startRadar
    }));

    toolbar.add(new Ext.Toolbar.Button({
        iconCls : 'delete',
        tooltip : '删除动画',
        handler : function(e) {
            if (totRadars > 0) {
                for (var i = 0; i < totRadars; i++)
                    map.removeLayer(radars[i]);
            };

            radars = [];
            radnames = [];
            totRadars = 0;
            loopable = false;

            Ext.DomHelper.overwrite("radar_text", {
                html : ''
            });
        }
    }));

    addSeparator(toolbar);

    var layer_store = new Ext.data.Store({
        proxy : new Ext.data.HttpProxy({
            url : '/map/get_cell_layer'
        }),

        reader : new Ext.data.JsonReader({
            totalProperty : 'results',
            root : 'rows',
            fields : [{
                name : 'date',
                type : 'string'
            }]
        })
    });

    layer_store.load();

    toolbar.add(new Ext.form.ComboBox({
        id : 'select_combo',
        emptyText : 'Select',
        mode : 'local',
        triggerAction : 'all',
        store : layer_store,
        displayField : 'date',
        valueField : 'date',
        listeners : {
            select : function(f, r, i) {

                var new_cell = f.getValue();
                var new_date;
                if (new_cell != '') {
                    // new_date = '_'+new_cell.split('_')[1];
                    new_date = '_' + new_cell;
                } else {
                    new_date = '';
                }

                map_tree = viewport.items['items'][1].items['items'][0];
                model = map_tree.model;

                if (cur_date != new_date) {

                    // delete all the layers
                    delete_model_layers(model[2]);

                    // set cur_date
                    cur_date = new_date;

                    // Add new layers
                    var opacity = 0.8;

                    add_model_layer("border900" + cur_date, opacity);
                    add_model_layer("field900" + cur_date, opacity);
                    for (var k = 0; k < 26; k++)
                        add_model_layer("traffic900" + cur_date + '_' + k,
                            opacity);
                    add_model_layer("fan900" + cur_date, opacity);
                    add_model_layer("border1800" + cur_date, opacity);
                    add_model_layer("field1800" + cur_date, opacity);
                    for (var k = 0; k < 26; k++)
                        add_model_layer("traffic1800" + cur_date + '_' + k,
                            opacity);
                    add_model_layer("fan1800" + cur_date, opacity);

                    // set session[:cur_date]
                    pars = 'cur_date=' + cur_date;
                    new Ajax.Request("/map/set_cur_date", {
                        method : 'POST',
                        parameters : pars,
                        onComplete : function(request) {
                            var new_node = {
                                text : '日期' + cur_date,
                                checked : false,
                                expanded : true,
                                children : []
                            };

                            new_node["children"][0] = {
                                text : 'GSM 900',
                                checked : false,
                                expanded : true,
                                children : [{
                                    text : "GSM900 边界",
                                    checked : false,
                                    layerName : "border900"
                                    + cur_date
                                }, {
                                    text : "GSM900 场强",
                                    checked : false,
                                    layerName : "field900"
                                    + cur_date
                                }, {
                                    text : "GSM900 话务",
                                    checked : false,
                                    expanded : false,
                                    children : [{
                                        text : "GSM900 话务-0点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_0"
                                    }, {
                                        text : "GSM900 话务-1点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_1"
                                    }, {
                                        text : "GSM900 话务-2点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_2"
                                    }, {
                                        text : "GSM900 话务-3点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_3"
                                    }, {
                                        text : "GSM900 话务-4点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_4"
                                    }, {
                                        text : "GSM900 话务-5点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_5"
                                    }, {
                                        text : "GSM900 话务-6点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_6"
                                    }, {
                                        text : "GSM900 话务-7点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_7"
                                    }, {
                                        text : "GSM900 话务-8点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_8"
                                    }, {
                                        text : "GSM900 话务-9点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_9"
                                    }, {
                                        text : "GSM900 话务-10点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_10"
                                    }, {
                                        text : "GSM900 话务-11点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_11"
                                    }, {
                                        text : "GSM900 话务-12点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_12"
                                    }, {
                                        text : "GSM900 话务-13点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_13"
                                    }, {
                                        text : "GSM900 话务-14点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_14"
                                    }, {
                                        text : "GSM900 话务-15点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_15"
                                    }, {
                                        text : "GSM900 话务-16点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_16"
                                    }, {
                                        text : "GSM900 话务-17点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_17"
                                    }, {
                                        text : "GSM900 话务-18点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_18"
                                    }, {
                                        text : "GSM900 话务-19点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_19"
                                    }, {
                                        text : "GSM900 话务-20点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_20"
                                    }, {
                                        text : "GSM900 话务-21点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_21"
                                    }, {
                                        text : "GSM900 话务-22点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_22"
                                    }, {
                                        text : "GSM900 话务-23点",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_23"
                                    }, {
                                        text : "GSM900 话务-上午",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_24"
                                    }, {
                                        text : "GSM900 话务-下午",
                                        checked : false,
                                        layerName : "traffic900"
                                        + cur_date
                                        + "_25"
                                    }]
                                }, {
                                    text : "GSM900 天线",
                                    checked : false,
                                    layerName : "fan900"
                                    + cur_date
                                }]
                            };

                            new_node["children"][1] = {
                                text : 'GSM 1800',
                                checked : false,
                                expanded : true,
                                children : [{
                                    text : "GSM1800 边界",
                                    checked : false,
                                    layerName : "border1800"
                                    + cur_date
                                }, {
                                    text : "GSM1800 场强",
                                    checked : false,
                                    layerName : "field1800"
                                    + cur_date
                                }, {
                                    text : "GSM1800 话务",
                                    checked : false,
                                    expanded : false,
                                    children : [{
                                        text : "GSM1800 话务-0点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_0"
                                    }, {
                                        text : "GSM1800 话务-1点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_1"
                                    }, {
                                        text : "GSM1800 话务-2点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_2"
                                    }, {
                                        text : "GSM1800 话务-3点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_3"
                                    }, {
                                        text : "GSM1800 话务-4点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_4"
                                    }, {
                                        text : "GSM1800 话务-5点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_5"
                                    }, {
                                        text : "GSM1800 话务-6点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_6"
                                    }, {
                                        text : "GSM1800 话务-7点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_7"
                                    }, {
                                        text : "GSM1800 话务-8点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_8"
                                    }, {
                                        text : "GSM1800 话务-9点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_9"
                                    }, {
                                        text : "GSM1800 话务-10点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_10"
                                    }, {
                                        text : "GSM1800 话务-11点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_11"
                                    }, {
                                        text : "GSM1800 话务-12点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_12"
                                    }, {
                                        text : "GSM1800 话务-13点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_13"
                                    }, {
                                        text : "GSM1800 话务-14点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_14"
                                    }, {
                                        text : "GSM1800 话务-15点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_15"
                                    }, {
                                        text : "GSM1800 话务-16点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_16"
                                    }, {
                                        text : "GSM1800 话务-17点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_17"
                                    }, {
                                        text : "GSM1800 话务-18点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_18"
                                    }, {
                                        text : "GSM1800 话务-19点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_19"
                                    }, {
                                        text : "GSM1800 话务-20点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_20"
                                    }, {
                                        text : "GSM1800 话务-21点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_21"
                                    }, {
                                        text : "GSM1800 话务-22点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_22"
                                    }, {
                                        text : "GSM1800 话务-23点",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_23"
                                    }, {
                                        text : "GSM1800 话务-上午",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_24"
                                    }, {
                                        text : "GSM1800 话务-下午",
                                        checked : false,
                                        layerName : "traffic1800"
                                        + cur_date
                                        + "_25"
                                    }]
                                }, {
                                    text : "GSM1800 天线",
                                    checked : false,
                                    layerName : "fan1800"
                                    + cur_date
                                }]
                            };

                            model[2] = new_node;

                            // reset model
                            var root = {
                                text : 'Root',
                                draggable : false, // disable root node
                                // dragging
                                id : 'source',
                                children : model,
                                leaf : false
                            };

                            // Pre-build the tree so that non-expanded
                            // nodes exist in the model.
                            var rootNode = buildTree(root);
                            map_tree.setRootNode(rootNode);
                            map_tree._fixupModel();

                            insert_layer("");
                        }
                    });

                } // end of if changed.
            }

        },
        width : 130
    }));

    toolbar.activate();
}

/*
 * Radar functions
 * 
 */
function startRadar() {
    if (!loopable && totRadars > 0) {
        loopable = true;
        loopRadar(0, loopable);
    }
}

function stopRadar() {
    loopable = false;
    Ext.DomHelper.overwrite("radar_text", {
        html : ''
    });
}

function loopRadar(sf, lp) {
    if (lp) {
        for (var i = 0; i < totRadars; i++)
            radars[i].setOpacity(0);
        radars[sf].setOpacity(1);

        // Set Layername
        Ext.DomHelper.overwrite("radar_text", {
            html : (sf + 1) + ' : ' + radnames[sf]
        });

        // Set Delay
        sf = sf + 1;
        if (sf >= totRadars) {
            sf = 0;
            var td = 2000;
        } else {
            var td = 1000;
        }

        var f = function() {
            loopRadar(sf, loopable)
        };
        var t = setTimeout(f, td);
    }
}

function showtranstool() {
    ttool = document.getElementById('transtool');
    tsld = document.getElementById('tslide');
    if (transtoolon == true) {
        ttool.src = '/images/layer-switcher-maximize.png';
        transtoolon = false;
        tsld.style.display = 'none';
    } else {
        ttool.src = '/images/layer-switcher-minimize.png';
        transtoolon = true;
        tsld.style.display = '';
    }
}

function rans() {
    transval = document.getElementById('transdisplay');
    outval = ((100 - transval.value) / 100);
    qlayer = map.getLayersByName(cur_map)[0];
    layer.setOpacity(outval);
}

function buildTree(attributes) {
    var node = new Ext.tree.TreeNode(attributes);

    var cs = attributes.children;
    node.leaf = !cs;
    if (!cs)
        return node;

    for (var i = 0; i < cs.length; i++) {
        // XXX This index is sometimes undefined on IE for unknown reason
        if (!cs[i]) {
            continue;
        }

        node.appendChild(buildTree(cs[i]));
    }
    return node;
}

function insert_layer(layer_name) {
    var graticule = map.getLayersByName("Graticule")[0];
    map.removeLayer(green);
    map.removeLayer(river);
    map.removeLayer(building);
    map.removeLayer(roads);
    map.removeLayer(vectorLayer_9);
    map.removeLayer(vectorLayer_18);
    map.removeLayer(vectorLayer);
    map.removeLayer(graticule);
    map.removeLayer(markers);
    if (layer_name != '')
        map.addLayer(layer_name);
    map.addLayers([green, river, building, roads, vectorLayer_9,
        vectorLayer_18, vectorLayer, graticule, markers]);
}

function add_model_layer(layer_name, opacity) {
    var favor_layer = new OpenLayers.Layer.WMS(layer_name, host_url, {
        layers : 'GZ125:' + layer_name,
        srs : 'EPSG:4326',
        transparent : true,
        format : format
    }, {
        reproject : false,
        opacity : opacity,
        visibility : false,
        isBaseLayer : false,
        displayInLayerSwitcher : false
    });
    map.addLayer(favor_layer);
}

function todayStr() {
    var today = new Date()
    return today.getMonth() + 1 + "/" + today.getDate() + "/"
    + (today.getYear() + 1900)
}

function getDiffDate(dadd) {
    // 可以加上错误处理
    var a = new Date();
    a = a.valueOf();
    a = a + dadd * 24 * 60 * 60 * 1000;
    a = new Date(a);
    return a.getMonth() + 1 + "/" + a.getDate() + "/" + (a.getYear() + 1900)
}

var msg = function(title, msg) {
    Ext.Msg.show({
        title : title,
        msg : msg,
        minWidth : 200,
        modal : true,
        icon : Ext.Msg.INFO,
        buttons : Ext.Msg.OK
    });
};

/**
 * Marker functions
 */
var markInfo = new Ext.TabPanel({
    activeTab : 0,
    height : 150,
    plain : true,
    defaults : {
        autoScroll : true
    },
    items : [{
        title : '地理信息',
        layout : 'fit'
    // autoLoad: {}
    }, {
        title : '基站信息',
        // autoLoad: {url: '/map/getbaseinfo', params: 'foo=bar&wtf=1'}
        layout : 'fit',
        items : grid_infoCell
    }, {
        title : '路测信息',
        // listeners: {activate: handleActivate},
        html : "I am tab 4's content. I also have an event listener attached."
    }],
    buttons : [{
        text : '动作'
    }, {
        text : '确定'
    }]
});

/**
 * Function: add
 */
function add(lon, lat, iconImage, info) {
    var size = new OpenLayers.Size(16, 25);
    var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
    var icon = new OpenLayers.Icon(iconImage, size, offset);
    var ll = new OpenLayers.LonLat(lon, lat);

    var AutoSizeAnchored = OpenLayers.Class(OpenLayers.Popup.Anchored, {
        'autoSize' : true
    });
    var popupClass = AutoSizeAnchored;
    var popupContentHTML = info;

    if (markers["markers"].length > 0) {
        var marker = markers["markers"][0];
        markers.removeMarker(marker);
        marker.destroy;
    };

    for (var i = map.popups.length - 1; i >= 0; --i) {
        map.removePopup(map.popups[i]);
    }

    addMarker(ll, popupClass, popupContentHTML, icon, true);
}

/**
 * Function: addMarker
 */
function addMarker(ll, popupClass, popupContentHTML, iconImage, closeBox,
    overflow) {
    var feature = new OpenLayers.Feature(gsat, ll);
    feature.closeBox = closeBox;
    feature.popupClass = popupClass;
    feature.data.popupContentHTML = popupContentHTML;
    feature.data.icon = iconImage;
    feature.data.overflow = (overflow) ? "auto" : "hidden";

    var marker = feature.createMarker();

    if (markWind != null) {
        markWind.close();
        markWind = null;
        hover.deactivate();
    }

    var markerClick = function(evt) {
        var grid_id = getGridid(ll.lon, ll.lat);
        if (markWind == null) {
            markWind = new Ext.Window({
                title : '综合信息',
                // tbar : logBar,
                floating : true,
                shadow : true,
                closeAction : 'hide',
                width : 400,
                height : 280,
                resizable : true,
                plain : true,
                draggable : true,
                collapsible : true,
                // collapsed: true,
                // minimizable: true,
                // minimized: true,
                maximizable : true,
                // maximized: true,
                listeners : {
                    close : function(w) {
                        w.restore();
                    },
                    maximize : function(w) {
                        w.setPosition(document.body.scrollleft,
                            document.body.scrollTop);
                    }
                },
                autoScroll : true,
                border : true,
                x : evt.clientX + 15,
                y : evt.clientY + 15,
                items : new Ext.TabPanel({
                    activeTab : 0,
                    height : 150,
                    plain : true,
                    defaults : {
                        autoScroll : true
                    },
                    items : [{
                        title : 'G900 ',
                        autoLoad : 'map/get900info?id=' + grid_id,
                        buttons : [{
                            text : '定位基站',
                            handler : function() {
                                url = "/map/get_field_900_by_gridid";
                                panto_url(url, grid_id);
                            }
                        }, {
                            text : '边界图',
                            handler : function() {
                                if (this.text == '边界图') {
                                    drawBorder9(grid_id, ll);
                                    this.setText('隐藏边界图');
                                } else {
                                    hidePoly_9();
                                    this.setText('边界图');
                                }
                            }
                        }, {
                            text : '场强图',
                            handler : function() {
                                pars = 'id=' + grid_id + '&prev='
                                + prev_900_id;
                                new Ajax.Request(
                                    "/map/gen_field9_view", {
                                        method : 'POST',
                                        parameters : pars,
                                        onComplete : function(
                                            request) {
                                            var id = request.responseText;

                                            // field900_20091227_6286_1
                                            // or field900_6286_1

                                            if (id != '0'
                                                && id.length < 100) {
                                                var ss = id
                                                .split('_')
                                                prev_900_id = ss[ss.length
                                                - 2];

                                                var layername = id;
                                                restore_layers(
                                                    layername
                                                    + ':0.8',
                                                    'Preview')

                                                // set showMode =
                                                // sector
                                                showMode = 1;
                                            }
                                        }
                                    });
                            }
                        }, {
                            text : '话务图',
                            menu : {
                                items : [{
                                    text : '0:00-1:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 0);
                                    }
                                }, {
                                    text : '1:00-2:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 1);
                                    }
                                }, {
                                    text : '2:00-3:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 2);
                                    }
                                }, {
                                    text : '3:00-4:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 3);
                                    }
                                }, {
                                    text : '4:00-5:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 4);
                                    }
                                }, {
                                    text : '5:00-6:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 5);
                                    }
                                }, {
                                    text : '6:00-7:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 6);
                                    }
                                }, {
                                    text : '7:00-8:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 7);
                                    }
                                }, {
                                    text : '8:00-9:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 8);
                                    }
                                }, {
                                    text : '9:00-10:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 9);
                                    }
                                }, {
                                    text : '10:00-11:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 10);
                                    }
                                }, {
                                    text : '11:00-12:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 11);
                                    }
                                }, {
                                    text : '12:00-13:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 12);
                                    }
                                }, {
                                    text : '13:00-14:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 13);
                                    }
                                }, {
                                    text : '14:00-15:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 14);
                                    }
                                }, {
                                    text : '15:00-16:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 15);
                                    }
                                }, {
                                    text : '16:00-17:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 16);
                                    }
                                }, {
                                    text : '17:00-18:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 17);
                                    }
                                }, {
                                    text : '18:00-19:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 18);
                                    }
                                }, {
                                    text : '19:00-20:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 19);
                                    }
                                }, {
                                    text : '20:00-21:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 20);
                                    }
                                }, {
                                    text : '21:00-22:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 21);
                                    }
                                }, {
                                    text : '22:00-23:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 22);
                                    }
                                }, {
                                    text : '23:00-24:00',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 23);
                                    }
                                }, {
                                    text : '上午',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 24);
                                    }
                                }, {
                                    text : '下午',
                                    handler : function() {
                                        add_traffic_layer('traffic900',
                                            grid_id, 25);
                                    }
                                }]
                            }

                        }]
                    }, {
                        title : 'G1800 ',
                        autoLoad : 'map/get1800info?id=' + grid_id,
                        buttons : [{
                            text : '定位',
                            handler : function() {
                                url = "/map/get_field_1800_by_gridid";
                                panto_url(url, grid_id);
                            }
                        }, {
                            text : '边界图',
                            handler : function() {
                                if (this.text == '边界图') {
                                    drawBorder18(grid_id, ll);
                                    this.setText('隐藏边界图');
                                } else {
                                    hidePoly_18();
                                    this.setText('边界图');
                                }
                            }
                        }, {
                            text : '场强图',
                            handler : function() {
                                pars = 'id=' + grid_id + '&prev='
                                + prev_1800_id;
                                new Ajax.Request(
                                    "/map/gen_field18_view", {
                                        method : 'POST',
                                        parameters : pars,
                                        onComplete : function(
                                            request) {
                                            id = request.responseText;
                                            if (id != '0'
                                                && id.length < 100) {
                                                ss = id.split('_')
                                                prev_1800_id = ss[ss.length
                                                - 2];

                                                layername = id;
                                                restore_layers(
                                                    layername
                                                    + ':0.8',
                                                    'Preview')

                                                // set showMode =
                                                // sector
                                                showMode = 2;
                                            }
                                        }
                                    });
                            }
                        }, {
                            text : '话务图',
                            menu : {
                                items : [{
                                    text : '0:00-1:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            0);
                                    }
                                }, {
                                    text : '1:00-2:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            1);
                                    }
                                }, {
                                    text : '2:00-3:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            2);
                                    }
                                }, {
                                    text : '3:00-4:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            3);
                                    }
                                }, {
                                    text : '4:00-5:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            4);
                                    }
                                }, {
                                    text : '5:00-6:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            5);
                                    }
                                }, {
                                    text : '6:00-7:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            6);
                                    }
                                }, {
                                    text : '7:00-8:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            7);
                                    }
                                }, {
                                    text : '8:00-9:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            8);
                                    }
                                }, {
                                    text : '9:00-10:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            9);
                                    }
                                }, {
                                    text : '10:00-11:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            10);
                                    }
                                }, {
                                    text : '11:00-12:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            11);
                                    }
                                }, {
                                    text : '12:00-13:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            12);
                                    }
                                }, {
                                    text : '13:00-14:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            13);
                                    }
                                }, {
                                    text : '14:00-15:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            14);
                                    }
                                }, {
                                    text : '15:00-16:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            15);
                                    }
                                }, {
                                    text : '16:00-17:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            16);
                                    }
                                }, {
                                    text : '17:00-18:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            17);
                                    }
                                }, {
                                    text : '18:00-19:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            18);
                                    }
                                }, {
                                    text : '19:00-20:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            19);
                                    }
                                }, {
                                    text : '20:00-21:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            20);
                                    }
                                }, {
                                    text : '21:00-22:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            21);
                                    }
                                }, {
                                    text : '22:00-23:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            22);
                                    }
                                }, {
                                    text : '23:00-24:00',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            23);
                                    }
                                }, {
                                    text : '上午',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            24);
                                    }
                                }, {
                                    text : '下午',
                                    handler : function() {
                                        add_traffic_layer(
                                            'traffic1800', grid_id,
                                            25);
                                    }
                                }]
                            }
                        }]
                    }, {
                        title : '当前图层',
                        border : false,
                        plain : true,
                        items : [new Ext.grid.PropertyGrid({
                            width : 200,
                            autoHeight : true,
                            border : false,
                            autoExpandColumn : 'value',
                            source : {
                                '01_grid_id' : '',
                                '05_场强值' : '',
                                '03_基站名称' : '',
                                '04_基站地址' : '',
                                '06_话务值' : '',
                                '02_基站名' : ''
                            },
                            viewConfig : {
                                forceFit : true,
                                scrollOffset : 0
                            // the grid will never have
                            // scrollbars
                            }
                        }), {}],
                        layout : 'fit'
                    }, {
                        title : '监视',
                        items : new Ext.TabPanel({
                            activeTab : 0,
                            height : 150,
                            plain : true,
                            tabPosition : 'bottom',
                            defaults : {
                                autoScroll : true
                            },
                            items : [{
                                title : '监视900',
                                items : [new Ext.grid.PropertyGrid(
                                {
                                    width : 200,
                                    autoHeight : true,
                                    border : false,
                                    autoExpandColumn : 'value',
                                    source : {
                                        '01_grid_id' : '',
                                        '02_距离' : '0m',
                                        '03_基站名' : '',
                                        '04_基站名称' : '',
                                        '05_基站地址' : '',
                                        '06_场强值' : '',
                                        '07_话务值' : ''
                                    },
                                    viewConfig : {
                                        forceFit : true,
                                        scrollOffset : 0
                                    // the grid will
                                    // never have
                                    // scrollbars
                                    }
                                })],
                                layout : 'fit'
                            }, {
                                title : '监视1800',
                                items : [new Ext.grid.PropertyGrid(
                                {
                                    width : 200,
                                    autoHeight : true,
                                    border : false,
                                    autoExpandColumn : 'value',
                                    source : {
                                        '01_grid_id' : '',
                                        '02_距离' : '0m',
                                        '03_基站名' : '',
                                        '04_基站名称' : '',
                                        '05_基站地址' : '',
                                        '06_场强值' : '',
                                        '07_话务值' : ''
                                    },
                                    viewConfig : {
                                        forceFit : true,
                                        scrollOffset : 0
                                    // the grid will
                                    // never have
                                    // scrollbars
                                    }
                                })],
                                layout : 'fit'
                            }]
                        }),
                        layout : 'fit'
                    }]
                }),
                // html : popupContentHTML,
                layout : 'fit',
                plain : true
            });
            markWind.show();
            markWind.el.setOpacity(0.85);
            hover.activate();
        } else {
            if (markWind.hidden) {
                markWind.show();
                hover.activate();
            } else {
                markWind.hide();
                hover.deactivate();
            }
        }
        OpenLayers.Event.stop(evt);
    };

    marker.events.register("click", feature, markerClick);
    markers.addMarker(marker);
}

/**
 * layers : 'green, river' string
 * 
 * 
 */
function restore_layers(layer_names, node_text) {

    if (layer_names != "") {

        var map_tree = viewport.items['items'][1].items['items'][0];
        var model = map_tree.model;

        layers = layer_names.split(",");

        if (model[model.length - 1].text == node_text) {
            var new_node = model[model.length - 1];
        } else {
            new_node = {
                text : node_text,
                checked : false,
                expanded : true,
                children : []
            };
        }

        for (var k = 0; k < layers.length; k++) {
            var layer_name = layers[k].split(":")[0];
            var opacity = layers[k].split(":")[1];

            var kk = k + new_node['children'].length;
            new_node["children"][kk] = {
                text : layer_name,
                checked : true,
                layerName : layer_name
            };

            // if the layers was not created, create it
            if (map.getLayersByName(layer_name).length == 0) {
                var favor_layer = new OpenLayers.Layer.WMS(layer_name,
                    base_url, {
                        layers : 'GZ125:' + layer_name,
                        srs : 'EPSG:4326',
                        transparent : true,
                        format : format
                    }, {
                        reproject : false,
                        opacity : opacity,
                        isBaseLayer : false
                    });
                map.addLayers([favor_layer, vectorLayer_9, vectorLayer_18,
                    markers]);
            } else {
                var favor_layer = map.getLayersByName(layer_name)[0];
                insert_layer(favor_layer);
                favor_layer.setOpacity(opacity);
                favor_layer.setVisibility(true);
            }
        };

        model[model.length - 1] = new_node;
        var root = {
            text : 'Root',
            draggable : false, // disable root node dragging
            id : 'source',
            children : model,
            leaf : false
        };

        // Pre-build the tree so that non-expanded nodes exist in the model.
        var rootNode = buildTree(root);
        map_tree.setRootNode(rootNode);
        map_tree._fixupModel();

        insert_layer("");
    // set active item
    // viewport.items["items"][1].getLayout().setActiveItem(0);
    }
}

/**
 * get_distiance(grid_id1, grid_id2)
 * 
 * 
 */
function get_distiance(grid1, grid2) {
    var x1 = 12572400 + ((grid1 - 1) % 25160) * 5;
    var y1 = 2575200 + ((grid1 - 1) / 25160) * 5;

    var x2 = 12572400 + ((grid2 - 1) % 25160) * 5;
    var y2 = 2575200 + ((grid2 - 1) / 25160) * 5;

    return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

function delete_model_layers(node) {
    if (typeof(node) == 'undefined')
        return;
    if (typeof(node.children) == 'undefined') { // leaf
        var layer_name = node.layerNames[0];
        var dlayer = map.getLayersByName(layer_name)[0];
        if (typeof(dlayer) != 'undefined')
            map.removeLayer(dlayer);
    } else {
        for (var k = 0; k < node.children.length; k++)
            delete_model_layers(node.children[k]);
    }
}

function add_traffic_layer(traffic, grid_id, key) {

    if (traffic == 'traffic900')
        pars = 'id=' + grid_id + '&prev=' + prev_900_hw + '&key=' + key
        + '&traffic=traffic900';
    else
        pars = 'id=' + grid_id + '&prev=' + prev_1800_hw + '&key=' + key
        + '&traffic=traffic1800';

    new Ajax.Request("/map/gen_traffic_view", {
        method : 'POST',
        parameters : pars,
        onComplete : function(request) {
            id = request.responseText;
            if (id != '0' && id.length < 100) {
                ss = id.split('_');
                (traffic == 'traffic900') ? prev_900_hw = ss[ss.length
                - 3] : prev_1800_hw = ss[ss.length - 3]
                var layername = id;
                restore_layers(layername + ':0.8', 'Preview')
            }
        }
    });
}
